Bash Debugging
Bash Debugging
Print Statements
• Adding echo statements to your script can help you inspect variable values,
command outputs, and execution flow.
Example:
#!/bin/bash
Example:
#!/bin/bash
set -x
• When you run the script with debug mode enabled (bash script.sh), each
line of the script will be printed to the terminal before execution, allowing you
to see the flow of execution and identify any issues.
1
Debugging on part(s) of the script
• Using the set Bash built-in you can run in normal mode those portions of the
script of which you are sure they are without fault, and display debugging
information only for troublesome zones.
• Say we are not sure what the somes commands (w) will do in the script, then
we could enclose it in the script like this:
#!/bin/bash
set -x # activate debugging from here
w
set +x # stop debugging from here
Installation on Debian/Ubuntu:
Installation on CentOS/RHEL:
Example
• Let’s start with a simple Bash script and learn how to debug it using Bashdb.
#!/bin/bash
echo -n "Enter The Number: "
read -r a
fact=1
while [ "$a" -ne 0 ]; do
fact=$((fact * a))
a=$((a - 1))
done
echo $fact
2
Debugging
• To debug this script with Bashdb, follow these steps:
bashdb factorial.sh
3. You’ll enter the Bashdb debugger prompt ((bashdb)). Now you can use vari-
ous commands to control the debugging process.
Debugging Commands
• Here are some commonly used commands in Bashdb:
Example
• Let’s debug our example script step by step:
bashdb factorial.sh
(bashdb) break 1
Example
3. The debugger will stop at the beginning of the factorial function. Use the
list command to see the code:
(bashdb) list
3
(bashdb) step
(bashdb) print $a
6. Continue stepping through the function until you reach the end.
7. Use the quit command to exit the debugger when you’re done.
References
• https://bashdb.sourceforge.net/bashdb.html
• https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html