Bash Tip: Tracing Execution
When your bash script is going haywire, and you’re having trouble sorting out why, one of the simplest ways to see what is going on is to use:
set -x
This turns on the xtrace shell option, which prints the commands the shell is executing with expanded arguments, as they are executed. From the man page:
expanded value of PS4, followed by the command and its
expanded arguments.
This shows you exactly what is going on as your script executes. Take the following, contrived shell script:
set -x
for i in $(seq 0 3)
do
if [[ $i -gt 1 ]]
then
echo $i
fi
done
exit 0
When executed, the script will print the following:
++ seq 0 3
+ [[ 0 -gt 1 ]]
+ [[ 1 -gt 1 ]]
+ [[ 2 -gt 1 ]]
+ echo 2
2
+ [[ 3 -gt 1 ]]
+ echo 3
3
+ exit 0
Note that the trace lines are prefixed with ‘+’ characters (in fact, whatever the value of $PS4 is), and regular output appears as normal. You can also see that the for loop and if conditions are displayed. This is all very handy for tracking down obscure problems.
One issue with tracing is the output can be very verbose, making the useful bits hard to find. If you have a rough idea of where the problem is, you can alleviate this problem by turning tracing on and off selectively around the interesting parts of the script (set +x turns it off). Happy scripting!
—
Automation crazy? Need a serious automated build server? Try pulse.
This entry was posted on Friday, June 2nd, 2006 at 12:21 am and is filed under Bash, Project Automation, Technology. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

January 23rd, 2008 at 9:28 pm
Dioktos says:Ever tried using ‘set -o xtrace’ and ‘set -o errexit’ with let?
set -o xtrace
set -o errexit
let i=0
echo $i
The last line will never be executed…