Code-Memo

Conditionals and loops

Tests in Bash

Prefer [[ ... ]]:

if [[ -f "$file" ]]; then
  echo "File exists"
fi

Common file tests

String / numeric tests

[[ "$a" == "x" ]]
[[ -n "$s" ]]          # non-empty
(( n > 10 ))           # arithmetic context

if / elif / else

if [[ "$mode" == "prod" ]]; then
  run_prod
elif [[ "$mode" == "dev" ]]; then
  run_dev
else
  echo "Unknown mode: $mode" >&2
  exit 2
fi

case

case "$1" in
  start) do_start ;;
  stop)  do_stop  ;;
  *) echo "Usage: $0 {start|stop}" >&2; exit 2 ;;
esac

Loops

for

for f in *.log; do
  [[ -e "$f" ]] || continue
  echo "$f"
done

while (read lines safely)

while IFS= read -r line; do
  echo "line=$line"
done < input.txt

until

until ping -c1 1.1.1.1 >/dev/null 2>&1; do
  sleep 1
done

Control flow