1. Overview
When errors happen in a Bash script, it can be helpful to know exactly where the error occurred. In this tutorial, we’ll learn how to show line numbers while executing a Bash script in debug mode.
2. The Problem Description
First, let’s write a helper script, which we’ll use throughout the tutorial:
$ cat unity_comparison.sh
#! /bin/bash
read -p "Enter the input: " num1
if [ -z "$num1" ]
then
echo "The number is empty"
exit 0
fi
if [ "${num1}" -eq 1 ]
then
echo "Number entered is 1"
else
if [ "${num1}" -ge 1 ]
then
echo "Number entered is greater than one."
else
echo "Number entered is less than one."
fi
fi
This script tests whether the number entered by the user is equal to 1, greater than 1, or less than 1.
Let’s execute this script in debug mode:
$ bash -x ./unity_comparison.sh
+ read -p 'Enter the input: ' num1
Enter the input: 4
+ '[' -z 4 ']'
+ '[' 4 -eq 1 ']'
+ '[' 4 -ge 1 ']'
+ echo 'Number entered is greater than one.'
Number entered is greater than one.
As we can observe, the output looks cluttered. Moreover, it’s difficult to correlate the debug output with the corresponding line number in the script. In the next section, we’ll take a look at ways to solve this issue.
3. Solution
The special shell variable PS4 defines the prompt that gets displayed when we execute a shell script in xtrace mode. The default value of PS4 is “*+*“:
$ echo $PS4
+
We can change the value of the PS4 variable to display line numbers in the debug prompt. To achieve this, we’ll use another special shell variable, LINENO.
Let’s use the export command to make the PS4 variable available to all the sub-processes of the current shell:
$ export PS4='Line $LINENO: '
Now, let’s execute our script in xtrace mode and verify the output:
$ bash -x ./unity_comparison.sh
Line 2: read -p 'Enter the input: ' num1
Enter the input: -13
Line 3: '[' -z -13 ']'
Line 8: '[' -13 -eq 1 ']'
Line 12: '[' -13 -ge 1 ']'
Line 16: echo 'Number entered is less than one.'
Number entered is less than one.
Now, the output is more readable, and we’re able to print the line numbers in the debug output.
Notably, here we exported the variable in the current shell so that it’s available to the shell script. Alternatively, we can also set the value of the PS4 variable within the script itself.
4. Conclusion
In this article, we learned how to display line numbers while executing a shell script in debug mode. We saw that we can add line numbers to debug output by tweaking the value of the PS4 variable.