a little madness

A man needs a little madness, or else he never dares cut the rope and be free -Nikos Kazantzakis

Zutubi

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:

-x After expanding each simple command, display the
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:

#! /usr/bin/env bash

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:

$ ./example.sh
++ 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.

Liked this post? Share it!

One Response to “Bash Tip: Tracing Execution”

  1. 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…

Leave a Reply