Bash Debugging Techniques
Debugging a Bash script means finding out why it does something different from what you expected. Bash makes this harder than most languages in a few specific ways: it continues after most errors by default, it silently splits and expands unquoted values, it runs parts of a pipeline in separate processes, and its error messages often describe a symptom far away from the cause. A script can print "done" and exit with status 0 after every single command in it has failed.
The good news is that almost every Bash bug belongs to a small set of known categories, and each category has a technique that exposes it. This lesson presents those techniques in the order in which they are most useful: checking syntax, reading error messages precisely, making invisible characters visible, seeing the exact arguments a command receives, tracing execution, adding debug output that can stay in the script, and producing a call stack when something fails. It ends with a reusable debugging library and a step-by-step investigation of a script with several bugs.
Start with a Method
Debugging is faster with a fixed routine than with random changes:
- Reproduce the problem with a command you can run again and again, ideally on a small copy of the data.
- Make the failure visible. Many Bash bugs are silent; the first goal is a clear error message or a wrong value you can point at.
- Find the first point where reality differs from your expectation. Check intermediate values from the start of the script forward until one is wrong. The bug is between the last correct value and the first wrong one.
- Explain the bug before fixing it. A fix you cannot explain often hides the problem instead of removing it.
- Rerun the reproduction, and keep it as a test (lessons 185 to 187).
The techniques below are tools for steps 2 and 3.
Checking Syntax Without Running: bash -n
bash -n reads a script and reports syntax errors without executing any command. It is safe to run on any script, including one that deletes files:
printf 'if true; then\n echo hi\n' > broken.sh
bash -n broken.sh; echo "[status $?]"
broken.sh: line 3: syntax error: unexpected end of file
[status 2]
The file has an if without its closing fi. Notice that the error points at line 3, the end of the file, and not at the if on line 1: Bash only notices that something is missing when it runs out of input. "Unexpected end of file" almost always means an unclosed if, loop, function body, quote, or $(, somewhere above the reported line.
bash -n checks grammar only. A misspelled command or variable name is perfectly valid grammar, so a clean result does not mean the script works. ShellCheck (lesson 162) finds many more problems without running the script, including most of the bugs in the example at the end of this lesson, and should be the second step.
Reading Error Messages Precisely
Bash error messages have a fixed structure: the script name, the line number, the command or word that failed, and the reason. Programs started by the script add their own messages, usually starting with the program's name. Reading every part carefully often points directly at the cause.
Pay special attention to how programs quote names in their messages. GNU coreutils programs such as cp, ls and rm print names in a form that makes unusual characters visible. A message like this one contains the whole explanation of a bug:
cp: cannot create regular file 'archive'$'\r''/': Not a directory
The target directory name is not archive/ but archive followed by $'\r', a carriage return character, followed by /. A carriage return is invisible in normal output; cp made it visible by switching to Bash's $'...' quoting for that one character. The next section explains where such characters come from.
Making Hidden Characters Visible
Text can contain characters that a terminal does not display: carriage returns, tabs, non-breaking spaces, a byte order mark at the start of a file. When a value "looks right" but comparisons with it fail or files named after it cannot be found, a hidden character is a strong suspect. Several tools display them:
cat -A archive.conf
od -c archive.conf
ARCHIVE_DIR=archive^M$
0000000 A R C H I V E _ D I R = a r c h
0000020 i v e \r \n
cat -A marks the end of each line with $ and shows control characters with a caret: ^M is the carriage return (character 13, written \r). od -c (octal dump, character mode) prints every byte of the file, with escapes such as \r and \n for control characters, and shows the byte offset at the start of each row.
The combination \r\n is the line ending that Windows uses. Files edited with some Windows editors, created in a browser text field, or checked out by Git with automatic line-ending conversion contain it. Bash treats only \n as the end of a line, so the \r becomes part of the last word on every line. A whole script with Windows line endings fails in a characteristic way:
printf 'echo start\r\ncd /tmp\r\n' > crlf.sh
bash crlf.sh
start
crlf.sh: line 2: cd: $'/tmp\r': No such file or directory
The fix is to remove the carriage returns, with sed -i 's/\r$//' file or the dos2unix program, and to prevent the problem from coming back, for example with a .gitattributes entry such as *.sh text eol=lf.
For a value that is already in a variable, declare -p prints the variable as Bash code that would recreate it exactly. It uses $'...' quoting whenever the value contains special characters, and it also shows the variable's type, which makes it the most precise way to inspect a variable:
source ./archive.conf
declare -p ARCHIVE_DIR
printf '%q\n' "$ARCHIVE_DIR"
declare -- ARCHIVE_DIR=$'archive\r'
$'archive\r'
printf '%q' gives the same quoted form for any value, including values that are not stored in a variable. Using echo "$var" for debugging is less reliable: it shows the value as the terminal displays it, so a trailing carriage return or space is invisible.
Seeing What a Command Really Receives
A large share of Bash bugs come from word splitting and globbing (lessons 53 and 55): an unquoted variable is split at spaces and its pieces are expanded as file name patterns, so a command receives different arguments than the code seems to say. The fastest way to see the real arguments is to put a command that prints them in place of the real command. printf with one placeholder repeats its format for each argument, so it prints one argument per line, with brackets that make the boundaries visible:
ARCHIVE_DIR=archive
f='reports/sales south.csv'
printf '<%s>\n' $f "$ARCHIVE_DIR/"
echo ---
printf '<%s>\n' "$f" "$ARCHIVE_DIR/"
<reports/sales>
<south.csv>
<archive/>
---
<reports/sales south.csv>
<archive/>
Without quotes, the file name became two arguments. A cp $f "$ARCHIVE_DIR/" in the script would therefore try to copy two files called reports/sales and south.csv. With quotes, it is one argument, as intended.
The same information is available without changing the command, by turning on execution tracing for the suspicious lines. set -x prints each command after all expansions, just before it runs, and set +x turns tracing off again:
set -x
cp $f "$ARCHIVE_DIR/"
set +x
+ cp reports/sales south.csv archive/
cp: cannot stat 'reports/sales': No such file or directory
cp: cannot stat 'south.csv': No such file or directory
+ set +x
The trace line, marked with +, shows that cp received three arguments. Tracing can also be enabled for a whole run with bash -x script.sh (lesson 126). The next lesson explains how to make traces more informative by adding file names, line numbers and function names to every trace line with the PS4 variable.
Debug Output That Can Stay in the Script
Printing intermediate values is the oldest debugging technique, and in Bash it is often the most efficient one. Two rules make it work well:
- Write debug output to standard error, with
>&2. Standard output often carries the script's real result into a pipe or a file, and debug messages must not mix into it. - Make it switchable. A
debugfunction that prints only when an environment variable is set can stay in the script permanently; when a problem appears months later,DEBUG=1 ./script.shbrings back all the diagnostic output without editing anything.
debug() {
if [[ -n ${DEBUG:-} ]]; then
printf 'DEBUG %s:%s: %s\n' "${FUNCNAME[1]:-main}" "${BASH_LINENO[0]}" "$*" >&2
fi
}
FUNCNAME is an array of the functions currently being executed: FUNCNAME[0] is debug itself and FUNCNAME[1] is the function that called it, or main at the top level of the script. BASH_LINENO[0] is the line from which debug was called. Every message therefore says where it came from, which matters once a script has many debug calls.
The function uses an if statement on purpose. The shorter form [[ -n ${DEBUG:-} ]] && printf ... returns a failing status when DEBUG is not set, because a function returns the status of its last command. In a script with set -e, every call of debug would then stop the script, but only when debugging is off, which is a confusing bug to have in a debugging tool. An if whose condition is false and that has no else returns status 0. ${DEBUG:-} expands to an empty string when the variable is not set, so the function also works under set -u.
Pipelines and Subshells
Some bugs are invisible even with tracing, because the code that misbehaves runs in a different process. Each command of a pipeline runs in its own subshell, a copy of the shell process. Variables changed in a subshell are changed only in that copy, which disappears when the command ends. Debug output that shows $BASH_SUBSHELL, the subshell nesting level, makes this visible, as the investigation below shows.
Pipelines also hide failures: the exit status of a pipeline is the status of its last command (lesson 120). After a pipeline, the array PIPESTATUS holds the status of every command in it:
curl -s http://nonexistent.invalid | wc -c
echo "statuses: ${PIPESTATUS[*]}"
0
statuses: 6 0
curl failed with status 6 ("could not resolve host"), but wc happily counted zero bytes and succeeded, so the pipeline as a whole reported success. PIPESTATUS must be read immediately after the pipeline, because the next command overwrites it. set -o pipefail makes the pipeline itself fail when any part fails.
Which Command Is Actually Running?
When a command behaves differently in a script than at the prompt, or differently on two machines, check what the name actually refers to. A name can be an alias, a function, a built-in command or a program somewhere in PATH, and Bash uses the first one it finds in that order. type -a lists every match:
type -a test
test is a shell builtin
test is /usr/bin/test
test is /bin/test
A script named test in the current directory is never run by typing test, because the built-in wins. Functions can shadow programs in the same way; type shows the function's code:
$ grep() { command grep --color=never "$@"; }
$ type grep
grep is a function
grep ()
{
command grep --color=never "$@"
}
Bash also remembers where it found each program, in a hash table, so it does not search PATH every time. If a new version of a program is installed in a directory earlier in PATH, an already running shell keeps using the old location until the table is cleared with hash -r:
$ mytool
old tool
$ # a new mytool is installed in a directory that comes earlier in PATH
$ mytool
old tool
$ type mytool
mytool is hashed (/tmp/bin1/mytool)
$ hash -r
$ mytool
new tool
A Call Stack When Something Fails
With set -e, a script stops at the first failing command, but Bash does not say where it stopped. The ERR trap (lesson 123) runs a command whenever a command fails, and inside it, several variables describe the failure:
$?is the exit status of the failed command, as long as it is read first.BASH_COMMANDis the text of the command that failed, as written in the script.FUNCNAME,BASH_SOURCEandBASH_LINENOtogether describe the call stack: which function called which, in which file, from which line.
A trap function can turn this into a traceback similar to those of Python or Java:
traceback() {
local status=$? i
printf 'ERROR: command "%s" failed with status %d\n' "$BASH_COMMAND" "$status" >&2
for (( i = 1; i < ${#FUNCNAME[@]}; i++ )); do
printf ' in %s at %s line %d\n' "${FUNCNAME[i]}" "${BASH_SOURCE[i]}" "${BASH_LINENO[i-1]}" >&2
done
}
set -o errtrace # functions, command substitutions and subshells inherit the ERR trap
trap traceback ERR
Inside the trap function, FUNCNAME[0] is traceback itself, so the loop starts at 1, the function in which the error happened. For each level i, BASH_SOURCE[i] is the file that contains the function, and BASH_LINENO[i-1] is the line in that function that was executing: the failing command for the first level, and the call of the next function for the others. Without set -o errtrace, the ERR trap is not active inside functions, which is where most errors happen.
local status=$? must be the first command in the trap function; any command before it would replace $? with its own status.
A Reusable Debugging Library
The helpers from this lesson fit into a small file that any script can load with source (lesson 95):
# debug.sh - debugging helpers for Bash scripts; source it near the top of a script
#
# debug MESSAGE... print MESSAGE to stderr, with function and line, when DEBUG is set
# debug_vars NAME... print variables exactly (quotes, arrays, hidden characters) when DEBUG is set
# ERR trap on any failing command: the command, its status and the call stack
debug() {
if [[ -n ${DEBUG:-} ]]; then
printf 'DEBUG %s:%s: %s\n' "${FUNCNAME[1]:-main}" "${BASH_LINENO[0]}" "$*" >&2
fi
}
debug_vars() {
local name
[[ -n ${DEBUG:-} ]] || return 0
for name in "$@"; do
{ declare -p "$name" 2> /dev/null || echo "$name is not set"; } |
sed 's/^declare -[-a-zA-Z]* /DEBUG var: /' >&2
done
}
traceback() {
local status=$? i
printf 'ERROR: command "%s" failed with status %d\n' "$BASH_COMMAND" "$status" >&2
for (( i = 1; i < ${#FUNCNAME[@]}; i++ )); do
printf ' in %s at %s line %d\n' "${FUNCNAME[i]}" "${BASH_SOURCE[i]}" "${BASH_LINENO[i-1]}" >&2
done
}
set -o errtrace # functions, command substitutions and subshells inherit the ERR trap
trap traceback ERR
debug_vars prints variables with declare -p, so hidden characters and array contents are shown exactly, and replaces the declare -- prefix with a shorter label. Because Bash variables are visible in the functions a function calls, debug_vars can also print the local variables of the function that calls it. The library is loaded relative to the script's own location, so it is found no matter where the script is started from:
source "$(dirname "${BASH_SOURCE[0]}")/debug.sh"
A Complete Example: Investigating a Broken Script
The script below is supposed to copy all CSV reports from the reports directory into an archive directory configured in archive.conf, and report how many it copied. The configuration file contains one line, ARCHIVE_DIR=archive, and the reports directory contains three files: sales-north.csv, returns.csv and sales south.csv, with a space in its name.
#!/usr/bin/env bash
# archive-reports.sh - copy the CSV reports into the directory named in archive.conf
source ./archive.conf # sets ARCHIVE_DIR
count=0
find reports -name '*.csv' | while read f; do
cp $f "$ARCHIVE_DIR/"
count=$((count + 1))
done
echo "archived $count reports"
Running it produces three error messages, a count of zero, and a successful exit status:
$ bash archive-reports.sh; echo "[status $?]"
cp: target 'archive'$'\r''/': No such file or directory
cp: cannot create regular file 'archive'$'\r''/': Not a directory
cp: cannot create regular file 'archive'$'\r''/': Not a directory
archived 0 reports
[status 0]
Bug 1: The Hidden Carriage Return
bash -n archive-reports.sh reports nothing, so the grammar is fine. The error messages are the best lead: all three show the target as 'archive'$'\r''/'. cat -A archive.conf confirms it, showing ARCHIVE_DIR=archive^M$: the configuration file was saved with Windows line endings, so the variable's value ends with a carriage return. Removing them fixes the first bug:
sed -i 's/\r$//' archive.conf
Bug 2: The File Name with a Space
The next run shows a different picture:
$ bash archive-reports.sh; echo "[status $?]"
cp: cannot stat 'reports/sales': No such file or directory
cp: cannot stat 'south.csv': No such file or directory
archived 0 reports
[status 0]
$ ls archive
returns.csv sales-north.csv
Two of three files were copied. The failed names, reports/sales and south.csv, are the two halves of reports/sales south.csv. The argument printing and tracing shown earlier in this lesson confirm that the unquoted $f was split into two arguments. Quoting it, cp "$f" "$ARCHIVE_DIR/", fixes this bug.
Bug 3: The Count That Stays at Zero
All files are copied now, but the script still reports archived 0 reports. Debug messages inside and after the loop, including the subshell level, show what happens:
debug() { if [[ -n ${DEBUG:-} ]]; then printf 'DEBUG %s:%s: %s\n' "${FUNCNAME[1]:-main}" "${BASH_LINENO[0]}" "$*" >&2; fi; }
...
find reports -name '*.csv' | while read f; do
cp "$f" "$ARCHIVE_DIR/"
count=$((count + 1))
debug "copied '$f', count=$count, subshell level=$BASH_SUBSHELL"
done
debug "after the loop: count=$count, subshell level=$BASH_SUBSHELL"
$ DEBUG=1 bash archive-reports.sh
DEBUG main:9: copied 'reports/sales south.csv', count=1, subshell level=1
DEBUG main:9: copied 'reports/returns.csv', count=2, subshell level=1
DEBUG main:9: copied 'reports/sales-north.csv', count=3, subshell level=1
DEBUG main:11: after the loop: count=0, subshell level=0
archived 0 reports
The counter works inside the loop and reaches 3, but the loop runs at subshell level 1: it is the last part of a pipeline, so it runs in a separate copy of the shell. When the pipeline ends, that copy disappears together with its count, and the main script still has its own count=0. The fix is to keep the loop in the main shell and feed it from find through process substitution (lesson 151): done < <(find ...). Only find runs in a separate process; the loop and its variables stay in the script.
Bug 4: Failure Reported as Success
The original script exited with status 0 while every copy failed, so a cron job or CI pipeline running it would never have noticed. Adding set -euo pipefail and the debugging library makes failures stop the script with a clear report.
The Fixed Script
#!/usr/bin/env bash
# archive-reports.sh - copy the CSV reports into the directory named in archive.conf
set -euo pipefail
source "$(dirname "${BASH_SOURCE[0]}")/debug.sh"
load_config() {
source ./archive.conf # sets ARCHIVE_DIR
debug_vars ARCHIVE_DIR
if [[ $ARCHIVE_DIR == *$'\r'* ]]; then
echo "archive.conf has Windows line endings; fix it with: sed -i 's/\r\$//' archive.conf" >&2
exit 1
fi
}
archive_reports() {
local f count=0
while IFS= read -r -d '' f; do
cp -- "$f" "$ARCHIVE_DIR/"
count=$(( count + 1 ))
debug "copied '$f', count=$count"
done < <(find reports -name '*.csv' -print0)
echo "archived $count reports"
}
load_config
archive_reports
Besides the four fixes, the loop now reads file names the safe way (lesson 112): find -print0 separates names with a null byte, which cannot occur in file names, read -d '' reads up to each null byte, IFS= keeps leading and trailing spaces, and -r keeps backslashes. cp -- ends option parsing, so a file name starting with - cannot be mistaken for an option. The configuration check turns the original mystery into a clear message if the carriage returns ever come back.
Running the Fixed Script
A normal run is quiet and correct:
$ bash archive-reports.sh; echo "[status $?]"
archived 3 reports
[status 0]
$ ls archive
returns.csv sales south.csv sales-north.csv
With DEBUG=1, the same script explains what it does, including the exact value of the configuration variable:
$ DEBUG=1 bash archive-reports.sh
DEBUG var: ARCHIVE_DIR="archive"
DEBUG archive_reports:20: copied 'reports/sales south.csv', count=1
DEBUG archive_reports:20: copied 'reports/returns.csv', count=2
DEBUG archive_reports:20: copied 'reports/sales-north.csv', count=3
archived 3 reports
When the archive directory is missing, the script no longer reports success. The traceback names the failed command, the function and line where it failed, and the line from which that function was called:
$ bash archive-reports.sh; echo "[status $?]"
cp: cannot create regular file 'archive/': Not a directory
ERROR: command "cp -- "$f" "$ARCHIVE_DIR/"" failed with status 1
in archive_reports at archive-reports.sh line 18
in main at archive-reports.sh line 26
[status 1]
And a configuration file with Windows line endings is detected and explained, with the debug output showing the hidden character:
$ DEBUG=1 bash archive-reports.sh; echo "[status $?]"
DEBUG var: ARCHIVE_DIR=$'archive\r'
archive.conf has Windows line endings; fix it with: sed -i 's/\r$//' archive.conf
[status 1]
All examples in this lesson were run with Bash 5.2 and GNU coreutils 9.4.
Interactive Debuggers
For long, complex scripts, a step-by-step debugger can be more convenient than traces and messages. bashdb, a separate open-source project, offers breakpoints, single-stepping and variable inspection in the style of gdb, and the Bash Debug extension for Visual Studio Code provides the same features in an editor. Both are built on Bash's own DEBUG trap, which runs a command before every simple command of the script; a minimal stepping effect can be had with trap 'read -rp "[$LINENO] $BASH_COMMAND "' DEBUG, which pauses before each command until Enter is pressed. In practice, most Bash bugs are found faster with the techniques above, because they belong to the small set of categories this lesson covered: hidden characters, word splitting, subshells, ignored failures and the wrong command being run.