command
Bash shell offers debugging options which can be turn on or off using set command.
=> set -x : Display commands and their arguments as they are executed.
=> set -v : Display shell input lines as they are read.
You can use above two command in shell script itself:
#!/bin/bashclear# turn on debug modeset -xfor f in *do file $fdone# turn OFF debug modeset +xls# more commands
You can replace standard
#!/bin/bash
with (for debugging)
#!/bin/bash -xv
Method # 3: Use of intelligent DEBUG function
Add special variable _DEBUG. Set to `on’ when you need to debug a script:
_DEBUG="on"
Put the following function at the beginning of the script:
function DEBUG(){ [ "$_DEBUG" == "on" ] && $@ || :}
Now wherever you need debugging simply use DEBUG function
DEBUG echo "File is $filename"
OR
DEBUG set -x
Cmd1
Cmd2
DEBUG set +x
When debugging done and before moving a script to production set _DEBUG to off
No need to delete debug lines.
_DEBUG="off" # set to anything but not to 'on'
Sample script:
#!/bin/bash_DEBUG="on"function DEBUG(){ [ "$_DEBUG" == "on" ] && $@ || :}DEBUG echo 'Reading files'for i in *do grep 'something' $i > /dev/null [ $? -eq 0 ] && echo "Found in $i file" || :doneDEBUG set -xa=2b=3c=$(( $a + $b ))DEBUG set +xecho "$a + $b = $c"
Save and run the script:
$ ./script.sh
Output:
Reading filesFound in xyz.txt file+ a=2+ b=3+ c=5+ DEBUG set +x+ '[' on == on ']'+ set +x2 + 3 = 5
Now set DEBUG to off
_DEBUG="off"
Run script:
$ ./script.sh
Output:
Found in xyz.txt file2 + 3 = 5
Above is a simple but quite effective technique. You can also try to use DEBUG as an alias instead of function.


百鸣[Baiming.org]欢迎您~