Sep 26, 2007

Make your Life easy for Debugging KSH Shell Script

One of the problem that’s comes while debugging the KSH script is to use echo command to check the script health.

Well KSH Script debugging in not very easy, one may want to test the script in a test environment and before publishing the script need to remove or comment debugging lines from source code.

Following mechanism could make you life easy.

Use following lines at the beginning of the script:

if [[ -z $DEBUG ]];then
alias DEBUG='# '
else
alias DEBUG=''
fi

Where ever you put a debugging line that is only for testing, use it in the following way:

DEBUG set –x

Or echo a parameter

DEBUG echo $PATH

Or set a parameter that is valid only during the test

DEBUG export LOGFILE=/tmp

Now the trick is before executing the script, set the DEBUG variable in the KSH shell as

# export DEBUG=yes

While the execution of the script, the DEBUG lines will be executed. Now when the script is published if you happen to forget deletion of the debuging lines; they shall never disturb the script execution.

Example
#!/usr/bin/ksh
#export DEBUG=yes # if u want to include debuging line

#export DEBUG="" # if u want to remove debuging line

if [[ -z $DEBUG ]];then
alias DEBUG='# '
else
alias DEBUG=''
fi

LOG_FILE=./out/script.out
DEBUG LOG_FILE=./out/script.out

function add {
a=$1 b=$2
return $((a + b))

}

# MAIN


DEBUG echo "test execution"
DEBUG echo "$(date) script execution" >>$LOG_FILEDEBUG


echo "if you do not know it:"

add 2 2echo " 2 + 2 = $?"

Make your life easy……

No comments: