Exterminating bugs in bash

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
3,055
Reaction score
2,783
Credits
26,583

Debugging Bash Scripts with set -x​

Debugging Bash scripts can be challenging, especially when dealing with complex logic and multiple commands. One powerful tool for debugging is the set -x command, which enables a mode of the shell where all executed commands are printed to the terminal. This helps you trace the execution flow and identify where things might be going wrong.

How to Use set -x​

To enable debugging with set -x, you can add the command at the beginning of your script or before the section you want to debug. To disable it, use set +x.

Example Commands​

Code:
#!/bin/bash

# Enable debugging
set -x

# Your script commands here

# Disable debugging
set +x

Sample Bash Script with a Problem​

Let's create a sample Bash script that has a problem. We'll use set -x to identify and fix the issue.

Code:
#!/bin/bash

# Enable debugging
set -x

# Sample script with a problem
echo "Starting the script..."
number=10
result=$((number / 0))  # This will cause a division by zero error
echo "The result is $result"

# Disable debugging
set +x

echo "Script completed."

Running the Script​

When you run the script, you'll see the following output:

Code:
+ echo 'Starting the script...'
Starting the script...
+ number=10
+ result=$((number / 0))
./sample_script.sh: line 8: division by 0 (error token is "0")
+ echo 'The result is '
The result is 
+ set +x
Script completed.

Identifying the Problem​

From the output, you can see that the script stops at the line where the division by zero occurs. The set -x command helps you pinpoint the exact location of the error.

Fixing the Problem​

To fix the problem, you can add a check to ensure the divisor is not zero before performing the division:

Code:
#!/bin/bash

# Enable debugging
set -x

# Sample script with a problem fixed
echo "Starting the script..."
number=10
divisor=2

if [ $divisor -ne 0 ]; then
  result=$((number / divisor))
  echo "The result is $result"
else
  echo "Error: Division by zero"
fi

# Disable debugging
set +x

echo "Script completed."

Conclusion​

Using set -x in your Bash scripts is a simple yet effective way to debug and trace the execution flow. By enabling this mode, you can quickly identify and fix issues in your scripts,
 

Staff online


Top