The absolute easiest would be to insert the following line after the hashbang line:
echo() { :; }
When you want to re-enable, either delete the line or comment it out:
#echo() { :; }
If you're not using echo
but printf
, same strategy, i.e.:
printf() { :; }
If you absolutely need to actually echo/printf something, prepend the builtin
statement, e.g.:
builtin echo "This 'echo' will not be suppressed."
This means that you can do a conditional output, e.g.:
echo () {
[[ "$SOME_KIND_OF_FLAG" ]] && builtin echo $@
}
Set the SOME_KIND_OF_FLAG
variable to something non-null, and the overridden echo
function will behave like normal echo
.
EDIT: another alternative would be to use echo
for instrumenting (debugging), and printf
for the outputs (e.g., for piping purposes). That way, no need for any FLAG
. Just disable/enable the echo() { :; }
line according to whether you want to instrument or not, respectively.
Enable/Disable via CLI Parameter
Put these lines right after the hashbang line:
if [[ debug == "$1" ]]; then
INSTRUMENTING=yes # any non-null will do
shift
fi
echo () {
[[ "$INSTRUMENTING" ]] && builtin echo $@
}
Now, invoking the script like this: script.sh debug
will turn on instrumenting. And because there's the shift
command, you can still feed parameters. E.g.:
- Without instrumenting:
script.sh param1 param2
- With instrumenting:
script.sh debug param1 param2
The above can be simplified to:
if [[ debug != "$1" ]]; then
echo () { :; }
shift
fi
if you need the instrumenting flag (e.g. to record the output of a command to a temp file only if debugging), use an else
-block:
if [[ debug != "$1" ]]; then
echo () { :; }
shift
else
INSTRUMENTING=yes
fi
REMEMBER: in non-debug mode, all echo
commands are disabled; you have to either use builtin echo
or printf
. I recommend the latter.