Absolutely! Bash debugging is crucial to figure out why a script isn’t working as expected. Bash provides built-in options and techniques to debug scripts. I’ll give you a complete, structured guide.
Prints each command before executing it, showing how variables are expanded.
bash -x script.shExample:
#!/bin/bash
NAME="Mahin"
echo "Hello $NAME"Run with debug:
bash -x script.shOutput:
+ NAME=Mahin
+ echo 'Hello Mahin'
Hello Mahin
Prints each line as it is read, before execution.
bash -v script.shSyntax check only; does not execute the script.
bash -n script.shTurn on/off debug mode inside the script:
#!/bin/bash
echo "Before debug"
set -x # Start debugging
VAR=5
echo "Value of VAR: $VAR"
set +x # Stop debugging
echo "After debug"Exit the script immediately if any command returns a non-zero status.
#!/bin/bash
set -e
echo "Step 1"
ls non_existing_file # Script stops here
echo "Step 2"Treat unset variables as an error:
#!/bin/bash
set -u
echo $UNDEFINED_VAR # Errorset -euxo pipefail-e→ exit on error-u→ treat unset variables as errors-x→ print commands before executing-o pipefail→ fail if any command in a pipeline fails
You can customize the prefix for -x output:
#!/bin/bash
export PS4='+ ${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
set -x
myfunc() {
echo "Inside function"
}
myfuncOutput will show file name, line number, function name for each command.
Use set -x locally:
#!/bin/bash
myfunc() {
set -x
for i in {1..3}; do
echo "Loop $i"
done
set +x
}
myfuncRun a command when an error or signal occurs.
#!/bin/bash
trap 'echo "Error at line $LINENO"' ERR
false # triggers trap$LINENO→ line number where error occurred$BASH_COMMAND→ command being executed
Example:
trap 'echo "Command failed: $BASH_COMMAND at line $LINENO"' ERR- Print variables with
echoorprintf - Check if commands return expected values
- Use
set -xaround suspect sections
- Use small test scripts to isolate the problem.
- Test loops and conditionals separately.
- Redirect debug output to a file:
bash -x script.sh > debug.log 2>&1- Combine
-xand-vfor maximum verbosity. - Use
shellcheck(external tool) for static analysis:
shellcheck script.sh✅ Summary
bash -x,set -x→ trace commandsset -e,set -u,set -o pipefail→ stop on errorstrap→ catch errors or signalsPS4→ detailed debug infoshellcheck→ static syntax and style checking
If you want, I can make a Markdown cheatsheet with all Bash debugging commands, flags, and traps, ready for reference.
Do you want me to do that?