So this is the final chapter for shell script tutorial. If you have followed and executed all the above programming examples, you might have stumbled upon many errors. Some errors are easy to fix; some take hours to check where the exact issue is.
In this chapter, I mention few points that I use for debugging purpose.
12.1 -x option:
This option is used to know step by step how your code is executing.
Consider below simple if statement:
#!/bin/bash val=5 if [ $val -eq 5 ] then echo "The value is equal to 5" fi
Then run the script as:
"sh -x myScript.sh"
Then the output will be:
+ val=5 + [ 5 -eq 5 ] + echo The value is equal to 5 The value is equal to
As you can see, it will substitute the “$val” value step by step and you can check where the code has gone wrong.
You can also add “-x” value in the starting line of the script as:
"#!/bin/bash set -x "
12.2 dos2unix command
Whenever you copy paste the code from internet or from other documents, sometimes you will receive an error like “binary operator expected” even though the script is error free. This is because the format of ASCII character will be different for windows and Linux. Hence to convert dos format to Unix format use “dos2unix <filename>”.
12.3 www.shellcheck.net
You can also use “www.shellcheck.net”. This website will check the error in your code and outputs the result.