← Knowledge Base
BashReference note1 min read · updated 2026-11-27

Bash conditions and loops

if, test operators, for, while and case, with the patterns that actually come up in scripts.

bashscriptingloops
if [[ -f "$file" ]]; then echo "exists"; elif [[ -d "$file" ]]; then echo "dir"; else echo "no"; fi

# useful tests: -f file  -d dir  -e exists  -s non-empty  -r readable  -x executable
#               -z "$s" empty string   -n "$s" non-empty   "$a" == "$b"   $n -gt 5   $n -le 3

for f in *.log; do gzip "$f"; done
for i in {1..5}; do echo "$i"; done
while read -r line; do echo "$line"; done < input.txt

case "$1" in
  start) echo starting ;;
  stop|halt) echo stopping ;;
  *) echo "usage: $0 start|stop" ;;
esac

Prefer [[ ... ]] over [ ... ] in Bash: no word splitting, and == / =~ (regex) work. Always use read -r.