Debugging with set -x and ShellCheck
Find shell script bugs by tracing execution with set -x and a custom PS4, checking syntax with bash -n, and linting with ShellCheck before you run.
Strict mode - set -e, -u and pipefailWord splitting and the order of expansionConditionals with if, test and double bracketsLoops - for, while and until
Debugging with set -x and ShellCheck
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `set -x`, or running `bash -x script`, prints each command after expansion with a `+` prefix, so you see the exact words the shell ran.
- Set `PS4='+ ${BASH_SOURCE##*/}:${LINENO}: '` to put the file name and line number in every trace line. Use `set -x` and `set +x` to trace only a region.
- `bash -n script` checks syntax without running anything. It catches a missing `fi` but not logic errors.
- ShellCheck is a static linter that finds quoting, comparison and portability bugs before you run, and gives each a code such as SC2086 that you can look up.
- Silence a ShellCheck warning you have decided to accept with a `# shellcheck disable=SCxxxx` comment on the line above, and say why.
When the script does something you didn’t write
At some point a script will do the wrong thing, and staring at it won’t tell you why. Shell scripts are hard to debug by reading, because what runs isn’t the text you wrote. It’s the text after quotes, variables, globs and substitutions have been resolved. A good debugging tool for a shell script has to show you the expanded commands. Bash has one built in, and there is a second tool that finds many bugs without running the script at all.
Here is a script with several mistakes in it. It should list log files with more than four server errors.
#!/usr/bin/env bash
# buggy: summarise each log, flag files with many errors
limit=4
for f in $(ls logs); do
errors=`awk '$8 >= 500' logs/$f | wc -l`
if [ $errors > $limit ]; then
echo "$f: too many errors ($errors)"
fi
done
I put two files in logs/, one named mon.log and one named tue night.log, each with 40 lines, five server errors apiece. Run it:
$ ./buggy.sh; ls
mon.log: too many errors ( 5)
awk: can't open file logs/tue
source line number 1
tue: too many errors ( 0)
awk: can't open file logs/night.log
source line number 1
night.log: too many errors ( 0)
4
buggy.sh
fixed.sh
logs
It reports “too many errors” for files with zero errors, splits tue night.log in two, and has created a file named 4 in the current directory. Three bugs, and none of them says “error”.
Tracing with set -x
bash -x ./buggy.sh, or set -x inside the script, makes Bash print each command after expansion, prefixed with +. Extra + signs mean nesting, such as a command substitution.
$ bash -x ./buggy.sh 2>&1 | sed -n 5,10p
++ wc -l
+ errors=' 5'
+ '[' 5 ']'
+ echo 'mon.log: too many errors ( 5)'
mon.log: too many errors ( 5)
+ for f in $(ls logs)
The + '[' 5 ']' line is the giveaway. The test that should have compared two numbers received exactly one argument, 5, and a one-word test is true whenever the word is non-empty. The > $limit had already been consumed as a redirection into the file 4. You can’t see that from the source, but the trace shows it at once.
Narrow the trace with set -x before the suspect part and set +x after. Make it say where each line came from:
$ PS4='+ ${BASH_SOURCE##*/}:${LINENO}: ' bash -x ./buggy.sh 2>&1 | sed -n 1,4p
+ buggy.sh:3: limit=4
++ buggy.sh:4: ls logs
+ buggy.sh:4: for f in $(ls logs)
++ buggy.sh:5: awk '$8 >= 500' logs/mon.log
PS4 is the prompt Bash prints before a traced command. Bash expands it each time, so ${LINENO} is current. Related: set -v echoes each line as it is read, before expansion.
Checking syntax without running: bash -n
Some mistakes stop a script from even starting. bash -n parses a script and reports syntax errors without executing a single command, which makes it safe on anything:
$ bash -n brk.sh; echo "bash -n status: $?"
brk.sh: line 4: syntax error: unexpected end of file from `if' command on line 2
bash -n status: 2
That file had an if with no fi. bash -n on buggy.sh exited 0 with no output, because the syntax is valid and the bugs are in the logic. For those, you need a tool that reads the script and knows common mistakes.
ShellCheck
ShellCheck is a static analyser for shell scripts. It doesn’t run your code. It parses it and checks it against a long list of known pitfalls, each with a code you can look up on its wiki. Run it on buggy.sh, version 0.11 here:
In buggy.sh line 4:
for f in $(ls logs); do
^--------^ SC2045 (error): Iterating over ls output is fragile. Use globs.
In buggy.sh line 5:
errors=`awk '$8 >= 500' logs/$f | wc -l`
^-- SC2006 (style): Use $(...) notation instead of legacy backticks `...`.
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
In buggy.sh line 6:
if [ $errors > $limit ]; then
^-----^ SC2086 (info): Double quote to prevent globbing and word splitting.
^-- SC2071 (error): > is for string comparisons. Use -gt instead.
All three bugs are named before the script runs: the ls loop, the unquoted $f, and the > comparison. ShellCheck exits with status 1 when it finds anything, so you can use it in a Git hook or CI job. Fixed version:
#!/usr/bin/env bash
# fixed: summarise each log, flag files with many errors
limit=4
for f in logs/*; do
errors=$(awk '$8 >= 500' "$f" | wc -l)
if (( errors > limit )); then
echo "${f##*/}: too many errors ($errors)"
fi
done
$ ./fixed.sh
mon.log: too many errors ( 5)
tue night.log: too many errors ( 5)
ShellCheck reports nothing on this one. The padding on the count is BSD wc.
A warning you’ve considered and chose to keep can be silenced for one line with a comment: # shellcheck disable=SC2086, ideally with the reason beside it. Don’t disable a code just to get a clean run. ShellCheck is in most package managers (brew install shellcheck on macOS), and I did not test installing it.
A working order
Run ShellCheck first, because it is free and finds the common mistakes. Use bash -n if the script won’t start, then bash -x with a line-numbered PS4. Finally, print suspect values with printf '%q\n', which showed a\ \ b for a value with two spaces, so hidden whitespace becomes visible.
About the video
Nick Janetakis’s “Linting and Improving Your Bash Scripts with ShellCheck” is 15 minutes 13 seconds and was published in May 2020. Its description has a full timestamp list, including running ShellCheck on a broken script (1:20), the shebang (1:59), going through warnings one at a time (2:34), local variables being Bash-only (3:18), quoting variable expansions (5:48), and ignoring a specific warning (10:54). I had no transcript. It is in English and covers ShellCheck, not set -x, so the tracing part comes from the lesson text and from the short You Suck at Programming set -x video, linked as a second view, which I judged by title.
Where this fits
That finishes the scripting-in-depth group. You can write, structure, and debug a real script. The roadmap now turns to what happens around scripts: processes, ps and the process tree.
Check yourself
What does `bash -x script.sh` show that running the script normally doesn't?
Every command after expansion, each prefixed with `+`. You can see the real arguments, such as `'[' 5 ']'` for a test, and which branch of a loop or `if` ran.
How do you make trace lines include the script name and line number?
Set `PS4`, for example `PS4='+ ${BASH_SOURCE##*/}:${LINENO}: ' bash -x script.sh`. Bash expands `PS4` at each traced line.
`bash -n` reports no errors on a script. Does that mean the script is correct?
No. It only parses the script for syntax errors, without running anything. A wrong comparison, an unquoted variable or a logic bug will not show up.
ShellCheck reports SC2086 on `rm $file`. What is it telling you, and what is the fix?
The unquoted variable will be split on whitespace and globbed. Quote it as `rm "$file"` unless you deliberately want splitting.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.