When a script does not work properly, we need to determine the location of the problem. The UNIX/Linux shells provide a debugging mode. Run the entire script in debug mode or just a portion of the script. To run an entire script in debug mode, add -x after the #!/bin/[shell] on the first line:
For Example :
#!/bin/sh -x
To run an entire script in debug mode from the command line, add a -x to the sh command used to execute the script:
$ sh -x script_name
Debug Statement Options
Run several portions of a script in debug mode by placing the set -x option at the point where debugging is to begin and the set +x option where you want it to stop. Do this as many times in the script as you want. The debug options are shown in Table below:
Option | Meaning |
---|---|
set -x | Prints the statements after interpreting metacharacters and variables |
set +x | Stops the printing of statements |
set -v | Prints the statements before interpreting metacharacters and variables |
set -f | Disables file name generation (using metacharacters) |
The set -v statement is similar to set -x, except, it shows the statement line before the shell performs any interpretation or substitution. When you use these two options, with set -xv, the shell displays the statement lines both before and after interpretation and substitution, so that you can see how the shell has used the statement line in the script.
For the following statement in a shell script:
echo $HOME # echo the HOME directory path
The statement line, before interpretation (set -v) is:
echo $HOME # echo the HOME directory path
The statement line, after interpretation (set-x) is:
+ echo /home/user
If both options are turned on, the -v line is always displayed before the -x line. Also, the + character does not precede the -v line.
Example of Debug Mode With the set -x Option
The following example shows the debug mode turned on for the script and turned off at the end.
# cat script.sh #!/bin/sh set -x echo "Your home is : $HOME" set +x
# ./script.sh + echo 'Your home is : /home/user' Your home is : /home/user + set +x
Example of Debug Mode With the set -v Option
The following example shows the -v debug mode turned on for the script. This option:
- Prints the statement prior to executing but without a leading + (unlike what the -x option displays).
- Does not translate metacharacters; therefore, it prints the statement exactly as it is in the script.
- Prints comment lines.
# cat script.sh #!/bin/sh set -v echo "Your home is : $HOME" set +v
# ./script.sh echo "Your home is : $HOME" Your home is : /home/user set +v