Bourne Shell Scripting/Parameters
From Wikibooks, the open-content textbooks collection
[edit] Debugging Flags
Its highly recommended that the first line of any bourne-shell script is :
#!/bin/sh
( see earlier section TBD )
To switch on debugging add in the '-x' flag to this line; for example:
#!/bin/sh -x echo hello
Running this gives:
+ echo hello hello
Before the 'echo' command is run by the shell, it outputs the command and arguments preceded with the '+' symbol, then the actual result of the command can be seen.
This second simple example, shows how environment variables are dealt with in this mode:
#!/bin/sh -x MYVAR=hello echo $MYVAR
Running this gives:
MYVAR=hello + echo hello hello
Note that when the 'echo' is run, the variable 'MYVAR' is resolved as 'hello' in the output; and you will not be able to tell from this alone that there was an enviroment variable involved here.
Note earlier on , that you can see the variable being set (note also that there is no preceding '+' symbol on that line).
Another flag that is sometimes useful to combine (although it can be run on its own as well) with the '-x' flag is the '-v' flag, which simply shows the 'source' lines of the script before they are run:
#!/bin/sh -xv
Reading the output from a complicated shell script can be tricky - you have to separate out the debug output from the normal output; so sometimes you might want to redirect the debug information to a separate file like this:
#!/bin/sh -x exec 2> /tmp/debuginfo.txt
Note that other outputs (like errors generated from commands) will also be placed in the '/tmp/debug.info.txt' file.
[edit] Breaking out of a script
When debugging a shell script, its sometimes to useful to exit out and certain points. Use the 'exit' built-in to do this - you can specify an output value with the command as well, which can be useful to 'trap' specific conditions (ie use different error conditions for different parts of the script).
#!/bin/sh -x echo hello exit 1
If you run this script, then you can also test the output status - using the "$?" built-in variable:
echo $? 1