shBash
BeginnerLesson 4 of 15

Conditions: if, [[ ]] and case – Bash

Branching, file and text tests, comparisons and pattern matching.

if evaluates the exit code of a command: 0 means true, anything else false. [[ ... ]] is Bash's modern test command (safer than the old [ ... ]): inside it you do not strictly have to quote variables, and patterns as well as &&/|| are allowed.

alter=20
if [[ $alter -ge 18 ]]; then
  echo "adult"
elif [[ $alter -ge 14 ]]; then
  echo "teenager"
else
  echo "minor"
fi

datei="server.log"
[[ -f "$datei" ]] && echo "File exists"
[[ -d /tmp ]]     && echo "/tmp is a folder"

The most important operators:

  • Files: -e exists, -f regular file, -d folder, -r/-w/-x readable/writable/executable, -s not empty.
  • Text: -z "$s" empty, -n "$s" not empty, == equal, != not equal, == with a pattern ([[ $s == a* ]]), =~ regex.
  • Numbers: -eq, -ne, -lt, -le, -gt, -ge – or arithmetically with (( a > b )).
  • Logic: && and, || or, ! not (inside [[ ]]: [[ -f a && -r a ]]).
name="Ada"
if [[ $name == A* ]]; then echo "starts with A"; fi
if [[ "2024-05-01" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then echo "ISO date"; fi
(( 10 > 9 )) && echo "arithmetic: 10 > 9"

# case: pattern matching, ideal for commands and options
befehl="stop"
case "$befehl" in
  start)       echo "starting" ;;
  stop|halt)   echo "stopping" ;;
  *)           echo "unknown: $befehl" ;;
esac
Warning[[ 10 > 9 ]] compares as text (lexicographically) and is therefore false: "10" < "9". For numbers use -gt or (( 10 > 9 )). Also: [[ $a == "abc" ]] (quotes on the right) compares literally; without quotes the right-hand side counts as a pattern.
TipYou can use any command as a condition: if grep -q ERROR server.log; then ... (-q = quiet, exit code only) or if ! command -v git >/dev/null; then echo "git missing"; fi.