Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Vaardigheden in dit hoofdstuk
- Fouten vinden en oplossen met ShellCheck en tracing
Fix missing quotes
A missing quote makes bash read on to the end of the file. The error then points to a line far away from the real mistake.
#!/bin/bash
number=1
if [ $number = 1 ]; then
echo "Number is equal to 1.
else
echo "Number is not equal to 1."
fitrouble
/home/me/bin/trouble: line 10: unexpected EOF while looking for matching `"'
/home/me/bin/trouble: line 13: syntax error: unexpected end of fileOp het werk
An editor with syntax colours shows a missing quote at once: everything after it has the "string" colour.
Fix missing or unexpected tokens
Forgetting then, fi, do, done or a ; gives "syntax error near unexpected token".
Watch for unexpected expansions
An empty or strange variable can change the command. Quotes protect you.
- Without quotes,
[ $number = 1 ]becomes[ = 1 ]when the variable is empty: a syntax error. - With quotes it becomes
[ "" = 1 ]: a valid test that is false.
Onthoud
Quote every variable expansion: "$var". It prevents most of these errors.
Know the logic errors
A logic error does not stop the script, but the result is wrong. Common types:
- Wrong condition: the
iftests the wrong thing, orthenandelseare swapped. - Off by one: a loop counts from 0 instead of 1, or stops one round too early.
- Unexpected situation: data or a file name the script did not expect (spaces, an empty value, a missing directory).
Program defensively
Check that each important step worked before the next one. A missing directory must not lead to deleting the wrong files.
cd $dir_name
rm *if [[ -d "$dir_name" ]]; then
if cd "$dir_name"; then
echo rm ./* # remove the 'echo' when the test is done
else
echo "cannot cd to '$dir_name'" >&2
exit 1
fi
else
echo "no such directory: '$dir_name'" >&2
exit 1
fiKnow set -e, set -u and pipefail
set -e stops a script when a command fails, set -u stops on unset variables, set -o pipefail makes a pipeline fail when any part fails. Many coding standards use them; the book advises careful use.
#!/bin/bash
set -euo pipefailCheck scripts with ShellCheck
shellcheck reads a script and warns about bugs and bad habits: missing quotes, unused variables, wrong tests. Use it on every script.
sudo dnf install ShellCheck
sudo apt install shellcheck
shellcheck my_script
In my_script line 5:
cd $dir_name
^-------^ SC2086: Double quote to prevent globbing and word splitting.
shellcheck -s bash my_library- ShellCheck knows the shell from the shebang. For files without a shebang (function libraries) use
-s bash. - More help: https://www.shellcheck.net
Op het werk
Run ShellCheck in your CI pipeline, so no script with warnings reaches the servers.
Watch out for file names
A file name may contain almost anything: spaces, new lines, and a leading -. A file called -rf looks like an option to rm.
Check all input
A script that accepts input must handle any input. Test it exactly: [[ $REPLY =~ ^[0-3]$ ]] allows only one digit from 0 to 3.
Notitie
"Design is a function of time": a quick one-time script can be simple; a script that others will run for years needs careful checks of every input.
Test with test cases
Test the script before you use it on real data. Comment out dangerous commands or put echo in front of them.
if [[ -d "$dir_name" ]]; then
if cd "$dir_name"; then
echo rm ./* # TESTING
fi
fi
exit # TESTINGGood test cases cover the normal case and the edge cases:
dir_nameis a real directory → the command runs.dir_namedoes not exist → a clear error, no action.dir_nameis empty → a clear error, no action.
Debug: find the area and trace
Find the area of the problem by commenting out parts. Then trace the script: bash prints every command before it runs.
bash -x trouble
+ number=1
+ '[' 1 = 1 ']'
+ echo 'Number is equal to 1.'
Number is equal to 1.set -x # Turn on tracing
if [ "$number" = 1 ]; then
echo "Number is equal to 1."
fi
set +x # Turn off tracing#!/bin/bash -xin the shebang traces the whole script.export PS4='$LINENO + 'shows the line number in each trace line.
Look at values while the script runs
Add echo lines that print variables at important places. Remove them when the bug is fixed.
number=1
echo "number=$number" # DEBUG
if [ "$number" = 1 ]; then
echo "Number is equal to 1."
fiSummary of the chapter
Quote variables, check every step, use ShellCheck, test edge cases, trace with bash -x.
1Why is rm ./* safer than rm *?
With ./ no file name can start with -, so no name is read as an option.
2Which command shows each line of a script as it runs?
bash -x script (or set -x inside the script).
3What does shellcheck do?
It analyses a shell script and warns about bugs and bad practices, like missing quotes.