Using Bash set -x to Help Debug Why a Script Isn't Working
Bash has an x flag or you can use set -x in a script to print a trace of commands and variables. It's really handy!
If you’re wondering why a variable isn’t outputting what you expect or why a
command you’re trying to run isn’t working as expected then running bash -x [YOUR_SCRIPT]
or defining set -x
in your script might be exactly what you
need.
In this video we’ll see how both work and how they help to debug shell scripts.
# Demo Video
Timestamps
- 0:08 – Going over the demo script really quick
- 1:07 – Running the script to demonstrate the error
- 2:23 – It worked manually but not in the script, hmm
- 3:11 – How
bash -x
helps us find the problem within seconds - 5:16 – A few ways to solve this specific error around passing in arguments
- 6:17 – Making ShellCheck happy
- 6:58 – Parsing arguments and one difference between
$*
and$@
with Bash - 9:09 – Why I like naming variables instead of using
$1
,$2
and$@
- 10:28 – Using
set -x
in your Bash script to applybash -x
by default - 11:28 – Does it with work POSIX complaint shell scripts?
Reference Links
- https://nickjanetakis.com/blog/replacing-make-with-a-shell-script-for-running-your-projects-tasks
- https://nickjanetakis.com/blog/linting-and-improving-your-bash-scripts-with-shellcheck
When was the last time -x helped you debug something? Let me know below.