Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 30Naam in het boek: Troubleshooting

Find and fix errors in scripts

Bigger scripts mean more errors. This chapter shows the common syntax errors (missing quotes, missing keywords, surprising expansions), logic errors, defensive programming (safe file names, checked input, ShellCheck), testing with test cases, and debugging with tracing.

  • 13 Lessen
  • 9 Commando's
  • 1 Labs

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

30.1

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.

trouble (with a missing quote)
#!/bin/bash
 
number=1
 
if [ $number = 1 ]; then
    echo "Number is equal to 1.
else
    echo "Number is not equal to 1."
fi
trouble
/home/me/bin/trouble: line 10: unexpected EOF while looking for matching `"'
/home/me/bin/trouble: line 13: syntax error: unexpected end of file

Op het werk

An editor with syntax colours shows a missing quote at once: everything after it has the "string" colour.

30.2

Fix missing or unexpected tokens

Forgetting then, fi, do, done or a ; gives "syntax error near unexpected token".

if [ $number = 1 ] then echo yes; fi
bash: syntax error near unexpected token `fi'
  • Without ; before then, bash reads then as an argument of [. The error appears at the next word bash cannot place.

Commando's in deze les

30.3

Watch for unexpected expansions

An empty or strange variable can change the command. Quotes protect you.

number=
[ $number = 1 ]
bash: [: =: unary operator expected
[ "$number" = 1 ]
echo $?
1

Onthoud

Quote every variable expansion: "$var". It prevents most of these errors.

30.4

Know the logic errors

A logic error does not stop the script, but the result is wrong. Common types:

  • Wrong condition: the if tests the wrong thing, or then and else are 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).

30.5

Program defensively

Check that each important step worked before the next one. A missing directory must not lead to deleting the wrong files.

dangerous
cd $dir_name
rm *
safe
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
fi
  • If cd fails in the dangerous version, rm * runs in the current directory.
  • The safe version checks that the directory exists and that cd worked.

Commando's in deze les

30.6

Know 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.

common header (with its limits)
#!/bin/bash
set -euo pipefail
  • The book does not recommend relying on set -e: it has many special rules (commands in if, &&, pipelines and subshells are not checked) and they change between bash versions.
  • Better: write real error handling (if ! cmd; then … fi, cmd || exit 1).
  • set -u is helpful to catch typos in variable names.

Commando's in deze les

30.7

Check 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.

30.8

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.

rm *
rm ./*
rm -- *
  • Start wildcards with ./: ./*, ./*.pdf. Then no name can start with -.
  • -- tells most commands "no more options after this".
  • The POSIX portable filename character set: only A–Z, a–z, 0–9, ., - and _, and do not start with -. Use only these in your own file names.

Commando's in deze les

30.9

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.

30.10

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.

test with echo
if [[ -d "$dir_name" ]]; then
    if cd "$dir_name"; then
        echo rm ./* # TESTING
    fi
fi
exit # TESTING

Good test cases cover the normal case and the edge cases:

  • dir_name is a real directory → the command runs.
  • dir_name does not exist → a clear error, no action.
  • dir_name is empty → a clear error, no action.

30.11

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.
trace only one part
set -x # Turn on tracing
if [ "$number" = 1 ]; then
    echo "Number is equal to 1."
fi
set +x # Turn off tracing
  • #!/bin/bash -x in the shebang traces the whole script.
  • export PS4='$LINENO + ' shows the line number in each trace line.

30.12

Look at values while the script runs

Add echo lines that print variables at important places. Remove them when the bug is fixed.

show a value
number=1
echo "number=$number" # DEBUG
if [ "$number" = 1 ]; then
    echo "Number is equal to 1."
fi

30.13

Summary 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.

Oefenen

Alle commando's in dit hoofdstuk