Unix Commands  «Prev  Next»
Lesson 1

Debugging Shell Scripts

When you create and run a shell script, you will see error messages from the shell indicating problems it detects with your script. This is most often due to syntax errors you have introduced during the process of writing the script. These messages help you identify the errors and correct them. Your script may also encounter problems processing user data. These errors will reveal themselves when the user enters invalid data or data that you have not anticipated. This module provides tools to locate and correct these errors. It also looks at common errors found in scripts. In this module, you will learn to:
  1. Use shell options to test each line of a script
  2. Identify syntax errors and logic errors
  3. Examine errors that involve the if statement
  4. Run a shell script with tracing options
  5. Examine errors involving input from the user
  6. Correct syntax errors in a given script
  7. Use the set command to trace a portion of a script
  8. Use the trap command to handle signals sent to a shell script

Debugging

By using the –n option to the bash command, you can check the syntax of your scripts without really executing any of the commands. If there is a syntax error in the script, the shell will report the error. If there are no errors, nothing is displayed.
The most commonly used method for debugging scripts is the set command with the –x option, or bash invoked with the –x option and the scriptname. These options allow an execution trace of your script. Each command from your script is displayed after substitution has been performed, and then the command is executed. When a line from your script is displayed, it is preceded with a plus (+) sign.

With the verbose option turned on, or by invoking the shell with the –v option (bash –v scriptname), each line of the script will be displayed just as it was typed in the script, and then executed.

Command Option, What It Does

bash –x scriptname Echo option 
Displays each line of script after variable substitutions and before execution.
bash –v scriptname Verbose option 
Displays each line of script before execution, just as you typed it.
bash –n scriptname Noexec option
Interprets but does not execute commands.
set –x
Turns on echoTraces execution in a script.
set +xTurns off echoTurns off tracing.

set -x enables a mode of the shell where all executed commands are printed to the terminal. It is clearly used for debugging, which is a typical use case for
set -x
which is printing every command as it is executed. This may help you to visualize the control flow of the script if it is not functioning as expected.