Geavanceerd
Zoeken inHow-to-gidsen
Zo zoek je
  • Typ de taak in je eigen woorden (poort vinden, firewall openen, schijf vol) of plak een foutmelding tussen aanhalingstekens.
  • Kies "Snel antwoord" om alleen de commando's te zien, of een gebied om in één vakgebied te blijven.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

How-to 94Build · Shell

How to write a safe Bash script

Most Bash scripts at work are written in 10 minutes — and then run as root for years. A few habits make the difference between "it deleted the wrong folder" and "it stopped with a clear error": strict mode, quoting every variable, checking inputs, cleaning up temp files, and letting ShellCheck find the rest. This how-to builds a safe template and explains each line.

  • 5 Lessen
  • 10 Commando's

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

94.1

The quick answer

backup-site.sh
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
 
usage() { echo "Usage: $0 SITE_DIR DEST_DIR" >&2; exit 2; }
[[ $# -eq 2 ]] || usage
src=$1
dest=$2
[[ -d "$src" ]] || { echo "No such folder: $src" >&2; exit 1; }
 
tmp=$(mktemp -d)
trap 'rm -rf -- "$tmp"' EXIT
 
tar -czf "$tmp/site.tar.gz" -C "$src" .
mkdir -p -- "$dest"
mv -- "$tmp/site.tar.gz" "$dest/site-$(date +%F).tar.gz"
echo "Backup written to $dest"
shellcheck backup-site.sh
bash -n backup-site.sh

Commando's in deze les

94.2

Step by step

  1. Strict mode — stop at the first problem instead of continuing in a broken state:
LineEffect
set -eExit when a command fails.
set -uExit when a variable is not set (no silent empty $DEST).
set -o pipefailA pipe fails if any part fails (not only the last).
IFS=$'\n\t'Do not split words on spaces.
  1. Quote every variable — "$file", "$@". Without quotes, a name with a space becomes two names, and an empty variable can turn rm -rf "$dir"/ into rm -rf /. Use -- before file arguments so names starting with - are not read as options.
  2. Check inputs early (as in the template): number of arguments, folders exist, values look right. Exit code 2 for wrong usage, 1 for errors.
  3. Temp files and clean-up: mktemp (never fixed names like /tmp/x), and trap … EXIT removes them on every exit — success, error, or Ctrl+C.
  4. Be careful with dangerous commands:
rm -rf -- "${dir:?dir is empty}/cache"

${dir:?msg} stops the script if dir is empty — rm never runs on /cache.

  1. Readable and debuggable: functions for steps, local variables, logs to stderr, and a debug switch:
bash -x backup-site.sh /var/www/shop /backup
  1. ShellCheck catches the classic bugs (missing quotes, cd without check, wrong tests) — run it in CI too:
dnf -y install ShellCheck
apt-get install -y shellcheck
shellcheck -S warning scripts/*.sh
  1. When not to use Bash: JSON/YAML handling, APIs, more than ~150 lines or complex logic → Python is clearer and safer.

94.3

Check that it worked

shellcheck has no warnings; the script stops with a clear message on wrong input (./backup-site.sh alone, a missing folder); the temp folder is gone after success and after a failure; and the exit code is right (echo $?).

Commando's in deze les

94.4

Common problems

ProblemCauseFix
unbound variableset -u and a variable that may be empty.${VAR:-default}, or check it first.
Script stops at grep that finds nothinggrep returns 1 when there is no match; set -e stops.grep … || true, or test it in if.
Works by hand, fails in cronDifferent PATH/environment.Full paths or set PATH at the top.
cd failed and the next command ran in the wrong folderNo check after cd.cd "$dir" || exit 1 (strict mode also helps).
$'\r': command not foundWindows line endings.dos2unix script.sh.
Secrets visible in ps or logsPassed as arguments or printed with -x.Read from files/env; turn off set -x around secrets.

94.5

Go further

1What does set -o pipefail change?

A pipeline fails when any command in it fails, not only the last one.

2How do you make sure rm -rf "$dir/cache" never runs with an empty dir?

Use ${dir:?message} — the script stops if dir is empty or unset.

Alle commando's in dit hoofdstuk