Sometimes it can be difficult to debug scripts. For example, a script only fails if it’s 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 don’t 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:
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.
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 won’t have to redirect the output each time you run the script, e.g. “./script > /tmp/script.log 2>&1″. In some cases you can’t 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.
No comments:
Post a Comment