I wrote some BASH code that executes a lot of external commands (causing side effects). So for developing and debugging I thought I wrap the executions in a shell function, so that the commands will either be executed or printed.
So that basic code is:
run()
{
if [ "$print_commands" -ne 0 ]; then
echo "$@"
else
"$@"
fi
}
Unfortunately most of the external commands output something when successful (like "success"), so I had been using > /dev/null
to redirect such output.
However there are some status queries that do output the status, and that cannot be discarded.
So obviously I cannot add > /dev/null
inside run
; also I don't want to add a second function that redirects, duplicating most code.
I tried a solution like this:
silence='>/dev/null'
run some_command with params $silence
The idea was to set silence
to the empty string when just printing the commands, which works, but when executing the commands I get:
error: unrecognized arguments: >/dev/null
Is there some half-way elegant solution without using eval
?
stderr
is not an option as there could be real error messages and I intend to paste the output to a terminal for execution (or into another script). See also the related question https://unix.stackexchange.com/q/726124/320598 – U. Windl Nov 24 '22 at 09:02set -n
– muru Nov 24 '22 at 09:03set -n
(how to use it here?). – U. Windl Nov 24 '22 at 09:20run
function. Instead of that, run the script withbash -n
, or runset -n
conditionally at the top of the script. – muru Nov 24 '22 at 09:38bash -n my_script
, then nothing is being executed, so nothing is being output. I don't see the usefulness ofset -n
still... – U. Windl Nov 24 '22 at 10:31-n
and-v
, sobash -nv
. – muru Nov 24 '22 at 10:34