I have bash script where i have echo before every command showing what is happening.
But i need to disbale echo when setting as cron job and then enable again if do some testing.
i find it very hard to go to each line and then add/remove comment
is there anything which i can include at top something like
enable echo or disable echo
so that i don’t have to waste time
The absolute easiest would be to insert the following line after the hashbang line:
When you want to re-enable, either delete the line or comment it out:
If you’re not using
echobutprintf, same strategy, i.e.:If you absolutely need to actually echo/printf something, prepend the
builtinstatement, e.g.:This means that you can do a conditional output, e.g.:
Set the
SOME_KIND_OF_FLAGvariable to something non-null, and the overriddenechofunction will behave like normalecho.EDIT: another alternative would be to use
echofor instrumenting (debugging), andprintffor the outputs (e.g., for piping purposes). That way, no need for anyFLAG. Just disable/enable theecho() { :; }line according to whether you want to instrument or not, respectively.Enable/Disable via CLI Parameter
Put these lines right after the hashbang line:
Now, invoking the script like this:
script.sh debugwill turn on instrumenting. And because there’s theshiftcommand, you can still feed parameters. E.g.:script.sh param1 param2script.sh debug param1 param2The above can be simplified to:
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:REMEMBER: in non-debug mode, all
echocommands are disabled; you have to either usebuiltin echoorprintf. I recommend the latter.