Vous êtes sur la page 1sur 1

August 13, 2007

Debugging Scripts
Sometimes it can be difficult to debug scripts. For example, a script only fails if its being executed by an application and you have no way of telling the application how the script should be executed to redirect the output. Or you simply dont want to redirect the output of the script each time you execute it. Adding the following lines at the beginning of the script can be very useful:
export PS4='$0.$LINENO+ ' exec > /tmp/script.log exec 2>&1 set -x

Example:
cat test #!/bin/bash export PS4='$0.$LINENO+ ' exec > /tmp/script.log exec 2>&1 set -x ls -ld /etc ls -ld /boot echo "This is a test" $ ./test $ cat /tmp/script.log ./test.6+ ls -ld /etc drwxr-xr-x 83 root root 7512 2006-07-22 16:49 /etc ./test.7+ ls -ld /boot drwxr-xr-x 5 root root 1960 2006-07-22 15:30 /boot ./test.8+ echo 'This is a test' This is a test $

These lines will turn on debugging and all information will be redirected to the log file. So you wont have to redirect the output each time you run the script, e.g. ./script > /tmp/script.log 2>&1. In some cases you cant do that if the script is invoked by an application. The PS4 builtin shell variable describes the prompt seen in debug mode. The $0 variable stands for the name of the script file itself. $LINENO shows the current line number within the script. The exec command redirects I/O streams. The first exec command redirects stdout stream 1 to /tmp/script.log. 2>&1 redirects stderr stream 2 to stdout stream 1. And set -x enables debugging.
Filed under: Linux, Scripting werner @ 8:48 pm

Vous aimerez peut-être aussi