Friday, June 8. 2007

Hints on writing (bash) shell scripts

Today a small hint that can save you a lot of debugging time when writing shell scripts. If you start your (bash) shell script with
set -u -e
unset parameters won't expand to nothing (-u) and the script ends immediately when one command fails (-e) unless it is part of a test (if, while, ||, etc., see bash(1)).

If you want to debug your shell script, you either insert echo commands throught your script, or you can just insert
set -v -x
at the top. This will turn on verbose mode (-v) in which bash will print the input lines as they are read. The execution trace (-x) mode will print the commands after expansion but before execution, so you can check if the command is invoked the way you intended.

I thought about posting similar hints for tcsh, but who is shell scripting in tcsh anyways?