Script Debugging

Sometimes a command in a script will fail for reasons that are not obvious. The -x flag is another flag common to both Bourne Shell and C shell that enables execute tracing, causing the shell to echo commands to the standard error before executing them. Using this, we can see the exact commands that are being executed after variable and globbing expansions. This might reveal a misconception we had about how to specify something.

We can tell a script to echo every command by adding a -x flag to the shell command:

#!/bin/sh -ex
        
#!/bin/csh -efx
        

Echoing every command is often overkill, however. In both Bourne shell and C shell, we can turn execute tracing on and off within the script:

#!/bin/sh -e

set -x      # Enable command echo
command
command
set +x      # Disable command echo
        
#!/bin/csh -ef

set echo    # Enable command echo
command
command
unset echo  # Disable command echo
        
Practice

Note

Be sure to thoroughly review the instructions in Section 2, “Practice Problem Instructions” before doing the practice problems below.
  1. What is execute tracing?

  2. How do we enable execute tracing for an entire script?

  3. How do we enable execute tracing for just a few commands in a script?