Debugging (Bash)
Naar navigatie springen
Naar zoeken springen
Here is a way to include a debugging option in Bash scripts, that isn't too obtrusive - I think it will be part of my 'personal coding standards' (2023.09).
Is the juice worth the squeeze?
The dilemma with adding debugging options:
- Does the added functionality really help, or does it only make the script or program more complex?
And like more often in life, the answer probably is: It depends.
However, it surely helps if the debugging functionality is really simple and has a little a footprint as possible.
Implementation
So far, debugging only involves sending data to the console.
Global variable $debug
- Use a global variable
$debug
as switch, rather than using command line switches - I hope that the name
$debug
isn't too generic to cause problems.
Test
- Test to decide whether debugging is enabled:
[ "$debug" ]
- This means, that debugging is enabled whenever this test evaluates to
true
. Any real value will evaluate totrue
- Disable debugging through e.g.:
unset debug
(also ok:debug=""
.
To illustrate this:
debug="blub" [ "$debug" ] && echo "Debugging is enabled" # True debug=0 [ "$debug" ] && echo "Debugging is enabled" # True unset debug [ "$debug" ] && echo "Debugging is enabled" # False
Display debugging info
When executing only one debugging command:
[ "$debug" ] && echo "Debugging is enabled"
When executing multiple commands, you can put them within ()
, which instantiates a subshell or within {}
, which doesn't. I prefer the latter approach. In that case:
- Include a
;
after each command, including the last command (or a newline, as in the following examples) - Don't forget the spaces around the curly braces.
E.g.:
[ "$debug" ] && { echo ""; echo "### assign_site_array"; }
This can also be extended over multiple lines. E.g.:
[ "$debug" ] && { echo "" echo "### assign_site_array" }
or
[ "$debug" ] && { echo "" echo "### assign_site_array" }