How to Safely Wrap and Intercept Linux Commands
There are times in automation scripting where a system binary behaves in a way that breaks your script (e.g., rejecting an expired OpenPGP signature policy), but you don't have configuration flags to change its behavior.
In these rare cases, you can temporarily "wrap" the binary with a shell script, inject your arguments, and use bash traps to ensure the system is restored to its original state when the script finishes.
The Problem
In our homelab project, Debian 13's strict OpenPGP signature policy (sqv) rejects the key format Kubernetes uses, preventing the apt repository from being added. The sqv binary doesn't offer a configuration file for this specific issue, but we can bypass it by appending a --policy-as-of flag to every invocation.
The Solution: A Temporary Wrapper
Here is the pattern to safely wrap a binary during a script's execution:
# 1. Check if the binary exists
if command -v sqv &>/dev/null; then
# 2. Rename the real binary
if [ ! -f /usr/bin/sqv.real ]; then
mv /usr/bin/sqv /usr/bin/sqv.real
fi
# 3. Create the wrapper script in its place
cat > /usr/bin/sqv <<'EOF'
#!/usr/bin/env bash
# Prepend the required flag, then forward all original arguments ("$@")
exec /usr/bin/sqv.real --policy-as-of 2025-01-01T00:00:00Z "$@"
EOF
chmod +x /usr/bin/sqv
fi
# 4. Set a trap to restore the original binary on exit
trap '[ -f /usr/bin/sqv.real ] && mv /usr/bin/sqv.real /usr/bin/sqv' EXIT
Why this works so well:
command -vGuard: Checking for the binary's presence dynamically is much more portable than hardcoding config file checks.- The
execKeyword: In the wrapper,execreplaces the shell process directly withsqv.real. This means there is no subshell overhead, and the process table remains clean. - The
trap EXITCatch-All:trap ... EXITguarantees the cleanup command runs regardless of how the script ends—whether it succeeds, fails with an error code, or the user pressesCtrl+C. This ensures your system isn't left with a permanently patched binary.