1) -x option to debug a shell script
Run a shell script using -x option
$bash -x script-name
$bash -x temp.sh farhat jahan
+ echo 'File Name: temp.sh'
File Name: temp.sh
+ echo 'First Parameter : farhat'
First Parameter : farhat
+ echo 'Second Parameter : jahan'
Second Parameter : jahan
+ echo 'Passed Parameters: farhat' jahan
Passed Parameters: farhat jahan
+ echo 'Passes Values : farhat jahan'
Passes Values : farhat jahan
+ echo 'Total no. of Parameters : 2'
Total no. of Parameters : 2
Note: You can even write
$bash -xv script-name
2)Use of set builtin command
Bash shell offers debugging option which can be turn on or off using set command.
- set -x : Display commands and their argument as the are executed.
- set -v : Display shell input lines as they are read.
#!/bin/bash
# turn on debug mode
set -x
echo "File Name: $0"
echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Passed Parameters: $@"
echo "Passes Values : $*"
# turn OFF debug mode
set +x
echo "Total no. of Parameters : $#"
$./temp.sh farhat jahan
+ echo 'File Name: ./temp.sh'
File Name: ./temp.sh
+ echo 'First Parameter : farhat'
First Parameter : farhat
+ echo 'Second Parameter : jahan'
Second Parameter : jahan
+ echo 'Passed Parameters: farhat' jahan
Passed Parameters: farhat jahan
+ echo 'Passes Values : farhat jahan'
Passes Values : farhat jahan
+ set +x
Total no. of Parameters : 2
Note: you can even replace #!/bin/bash with #!/bin/bash -xv for debugging
3)Use of intelligent DEBUG function.
Add special variable _DEBUG. Set it "on" when you need to debug a script
_DEBUG="on"
Keep the following function at the beginning of the script.
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@
}
Now whenever u want debug simply call the function.
DEBUG echo "ERROR:: file not found"
Note:When debugging is done you can set _DEBUG to off.
Example:
#!/bin/bash
_DEBUG="on"
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@
}
DEBUG echo "Calculating"
DEBUG set -x
a=5
b=3
c=$(( $a - $b ))
DEBUG set +x
echo "$a - $b = $c"
OUTPUT:
$./temp.sh
Calculating
+ a=5
+ b=3
+ c=2
+ DEBUG set +x
+ '[' on == on ']'
+ set +x
5 - 3 = 2
Tune toh pura codding kar di ... thoda explain bhi kar deti .. :)
ReplyDeleteLet me know wat u didnt understand. its about ways to do debugging in shell script. you can try he same code and run u'll get to know.:)
ReplyDeletefeel free to correct me :)