appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Bash scripting essentials

Lesson 1 of 412 minIntermediate

Variables, conditions, loops and exit codes: write a script you can trust.

A Bash script is a text file of commands. Start it with a shebang line so the system knows which interpreter to use, and make it executable.

backup.sh
#!/usr/bin/env bash
set -euo pipefail

src="${1:?usage: backup.sh SOURCE_DIR}"
stamp="$(date +%F)"
tar -czf "backup-$stamp.tar.gz" "$src"
echo "Saved backup-$stamp.tar.gz"
chmod +x backup.sh
./backup.sh /home/ana/docs

Safer defaults

  • set -e stops the script when a command fails.
  • set -u treats an unset variable as an error.
  • set -o pipefail makes a pipeline fail if any command in it fails.
  • Quote variables: "$src". Unquoted values are split on spaces and can break on file names with spaces.

Conditions and loops

if [[ -f "$file" ]]; then
  echo "exists"
elif [[ -d "$file" ]]; then
  echo "directory"
else
  echo "missing"
fi

for f in *.log; do
  gzip "$f"
done

Exit codes

Every command returns a number: 0 means success and anything else means failure. $? holds the last one, and && and || chain commands on it.

mkdir build && cd build
grep -q ERROR app.log || echo "no errors"

NoteUse shellcheck script.sh (a free linter) to find quoting mistakes and portability problems before they hurt you.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does set -u do?
2. Why quote "$file"?
Hintchmod with +x.

Key terms