How do you debug a Bash script?
BeginnerConceptShellCheck, debugging, testing, portability and security
Answer
bash -n script.sh # syntax check only, nothing runs
bash -x script.sh # trace every command after expansion
set -x; risky_part; set +x # trace just one section
bash -v script.sh # print lines as read (before expansion)
Read the + lines: they show the command after expansion, so you see exactly what an unquoted variable turned into. Combine with PS4 for file and line numbers, and with trap ... ERR for the failing line.
More on ShellCheck, debugging, testing, portability and security
What is ShellCheck and how do you use it in a team?BeginnerHow do you disable a ShellCheck warning, and when is that acceptable?IntermediateName the ShellCheck warnings you see most and what each means.IntermediateHow do you make `set -x` output more useful with `PS4`?IntermediateWhat is bats, and how do you test a script that calls external commands?IntermediateWhat is `shfmt` and why use it alongside ShellCheck?Beginner