Bash scripts, because of their nature and intended usage, are tricky to debug and test. In this short article let’s look at 3 common methods that developers use to debug bash shell scripts.
The following are the 3 commonly used methods:
echo
commandEnabling debugging mode
trap
command
The Good Old Echo
The echo
command is the console.log()
equivalent in the bash land. It is quite simple and can come in handy while debugging a script.
By using echo statements throughout your script, you can output the value of variables, the result of commands, and any other information that is useful in understanding how your script is working. For example, consider the following script:
#!/bin/bash
echo "Starting script"
VAR1="Hello"
VAR2="World"
echo "VAR1 is: $VAR1"
echo "VAR2 is: $VAR2"
echo "Concatenating variables..."
result="$VAR1 $VAR2"
echo "Result is: $result"
echo "Exiting script"
In this script, we use echo statements to output the value of variables VAR1 and VAR2, as well as the result of concatenating these variables. This output can be helpful in understanding how the script is working.
Although the scripts you’d encounter on production won’t be this simple, you get the idea of how this could be used.
The Debugging Mode
Another useful tool for debugging is the set
command. When you run the set -x
command in your script, it will enable debugging mode.
Keep reading with a 7-day free trial
Subscribe to BinaryWares to keep reading this post and get 7 days of free access to the full post archives.