← Full reference

Conditions and loops

if, [[ ]], test, case, for/while/until loops, reading a file line by line, break and continue

In bash a condition is any command: if looks at its exit code; 0 means "true", anything else means "false". [[ … ]], [ … ] and (( … )) are just commands that test an expression and return 0 or 1.

Syntax

if command; then
    …
elif other_command; then
    …
else
    …
fi

for x in list; do … done
while command; do … done
until command; do … done
case "$var" in pattern) … ;; esac

then and do can go on the same line after ; or on the next line. All of it can also be written on one line: for i in 1 2 3; do echo "$i"; done.

Three kinds of tests

FormWhat it is
[[ expression ]]bash's built-in test: no word splitting, supports patterns and regexes — use it by default
[ expression ], test expressionthe POSIX command; works in sh, but needs quotes around variables
(( expression ))arithmetic: true if the result is non-zero; (( n > 5 ))
commandany command: if grep -q root /etc/passwd; then …

File tests

TestTrue if…
-e paththe path exists (any type)
-f patha regular file
-d patha directory
-L path / -h patha symbolic link (even a broken one)
-s paththe file exists and is not empty
-r / -w / -x paththe current user has read / write / execute permission
-O path / -G paththe file's owner / group is the current user / their group
-p / -S / -b / -c pathnamed pipe / socket / block / character device
a -nt b / a -ot ba is newer / older than b by modification time
a -ef ba and b are the same file (hard or symbolic link)
-t 0descriptor 0 is a terminal (the script is running interactively)

Strings and numbers

TestTrue if…
-z "$s" / -n "$s"the string is empty / non-empty
"$a" = "$b" / "$a" != "$b"the strings are equal / not equal (== works in [[ ]])
$s == patternin [[ ]]: the string matches a glob (*.log); the pattern is unquoted
$s =~ regexin [[ ]]: matches an ERE; groups go to ${BASH_REMATCH[1]}…
"$a" < "$b"string a sorts before b alphabetically (in [ ] write \<)
-eq -ne -lt -le -gt -geinteger comparison: equal, not equal, <, <=, >, >=
-v namethe variable is set (even if empty)

Logic

FormWhere it works
[[ a && b ]], [[ a || b ]], [[ ! a ]], [[ ( a || b ) && c ]]inside [[ ]]
[ a ] && [ b ], [ a ] || [ b ], ! [ a ]between any commands
[ a -a b ], [ a -o b ]inside [ ]; obsolete, prefer &&/|| outside

case

ElementMeaning
pattern)a glob: *, ?, [0-9]; a|b) — several alternatives
*)everything else (put it last)
;;end of the branch, stop checking
;&also run the next branch without checking it
;;&keep checking the following patterns

Loops and control

FormWhat it does
for x in a b cover a list of words
for f in *.logover files matching a pattern
for i in {1..10} / {0..100..5}over a range (bounds must be literals, not variables)
for ((i=0; i<n; i++))C style; bounds can be variables
for xover the script's arguments ("$@")
while command / until commandwhile the command succeeds / while it fails
while : / while trueinfinite loop, exit with break
break / break 2leave the loop / two nested loops
continue / continue 2go to the next iteration of this / the outer loop
select x in a ba numbered menu from a list (reads stdin)

read

OptionWhat it does
-rdon't treat \ as an escape — always use it
IFS= read -r linekeep leading and trailing spaces of the line
IFS=: read -r a b csplit the line on :; extra fields go into the last variable
-a arrthe line's words go into an array
-p 'text'prompt before input
-sdon't echo input (passwords)
-n Nread exactly N characters without waiting for Enter
-t sectimeout; when it expires the exit code is greater than 128
-d charread up to this character instead of a newline (-d '' — up to \0)

Without variable names the line goes into $REPLY. At end of file read returns 1 — that's what ends a while read loop.

Examples

# the file exists and is not empty
if [[ -s /etc/hosts ]]; then echo "exists"; fi

# a number in a range
n=7
if (( n >= 1 && n <= 10 )); then echo "ok"; else echo "out of range"; fi

# by a command's exit code
if grep -q '^root:' /etc/passwd; then echo "root exists"; fi

# pattern and regular expression
f="report.csv"
[[ $f == *.csv ]] && echo "csv"
if [[ $f =~ ^([a-z]+)\.([a-z]+)$ ]]; then
    echo "name ${BASH_REMATCH[1]}, extension ${BASH_REMATCH[2]}"
fi

# short form instead of if
[[ -d /tmp/work ]] || mkdir /tmp/work

# case on an argument
case "$1" in
    start|run) echo "starting" ;;
    stop)      echo "stopping" ;;
    *)         echo "usage: $0 start|stop"; exit 1 ;;
esac

# loops
for i in {1..5}; do echo "$i"; done
for ((i = 0; i < 3; i++)); do echo "$i"; done
for f in /etc/*.conf; do echo "$f"; done

# a file line by line, fields separated by colons
while IFS=: read -r user _ uid _; do
    (( uid >= 1000 )) && echo "$user"
done < /etc/passwd

# skip and stop
for i in 1 2 3 4 5; do
    (( i == 2 )) && continue
    (( i == 4 )) && break
    echo "$i"                       # 1 3
done

# wait for a file to appear, but no more than 10 attempts
for i in {1..10}; do
    [[ -e /tmp/ready ]] && break
    sleep 1
done

Pitfalls

  • Spaces inside the brackets are required. [[-f x]] and [ "$a"="$b" ] don't work: [[ and ]] must be separate words, and = must be a separate argument.
  • Quote variables in [ ]. If v is empty, [ $v = x ] becomes [ = x ] — error "unary operator expected". [[ ]] doesn't have this problem.
  • > and < compare strings, not numbers. [[ 10 > 9 ]] is false ("1" sorts before "9"). For numbers: -gt or (( 10 > 9 )). And [ b > a ] actually creates a file named a.
  • Quotes disable patterns and regexes. [[ $f == "*.log" ]] compares with the literal string *.log. Keep a regex in a variable: re='^[0-9]+$'; [[ $s =~ $re ]].
  • A pattern with no matches stays as is. for f in *.zzz with no such files does one iteration with f='*.zzz'. Check [[ -e $f ]] || continue or enable shopt -s nullglob.
  • cat f | while read … runs in a subshell. Variables changed in the loop are gone after it. Write while … done < f.
  • A last line without \n is lost in while read. The fix: while read -r line || [[ -n $line ]].
  • for line in $(cat f) iterates over words, not lines. For lines, only while read.
  • {1..$n} doesn't work: brace ranges are expanded before variables. Use for ((i=1; i<=n; i++)) or seq.

See also

variables · exit-codes · redirection · regex