How to debug a Bash script if it has some bugs?
Common techniques like printing varibles out for checking apply for bash too.
For bash, I usually use 2 bash-specific techniques.
set -o errexit to the beginning of the script
errexit makes bash exit immediately if one statement’s return code is not 0. This way, you know which statement goes wrong.
bash -x your-script.sh
-x will make bash print statements executed so that you know what is going on.
set -x inside of your script.
#!/bin/bash set -x i=0 let i=i+1 echo $i
The execution of that script will print
+ i=0 + let i=i+1 + echo 1 1
By combining the 2 techniques together, which statement/step went wrong is printed out on the STDOUT.