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
| Form | What it is |
|---|
[[ expression ]] | bash's built-in test: no word splitting, supports patterns and regexes — use it by default |
[ expression ], test expression | the POSIX command; works in sh, but needs quotes around variables |
(( expression )) | arithmetic: true if the result is non-zero; (( n > 5 )) |
command | any command: if grep -q root /etc/passwd; then … |
File tests
| Test | True if… |
|---|
-e path | the path exists (any type) |
-f path | a regular file |
-d path | a directory |
-L path / -h path | a symbolic link (even a broken one) |
-s path | the file exists and is not empty |
-r / -w / -x path | the current user has read / write / execute permission |
-O path / -G path | the file's owner / group is the current user / their group |
-p / -S / -b / -c path | named pipe / socket / block / character device |
a -nt b / a -ot b | a is newer / older than b by modification time |
a -ef b | a and b are the same file (hard or symbolic link) |
-t 0 | descriptor 0 is a terminal (the script is running interactively) |
Strings and numbers
| Test | True if… |
|---|
-z "$s" / -n "$s" | the string is empty / non-empty |
"$a" = "$b" / "$a" != "$b" | the strings are equal / not equal (== works in [[ ]]) |
$s == pattern | in [[ ]]: the string matches a glob (*.log); the pattern is unquoted |
$s =~ regex | in [[ ]]: matches an ERE; groups go to ${BASH_REMATCH[1]}… |
"$a" < "$b" | string a sorts before b alphabetically (in [ ] write \<) |
-eq -ne -lt -le -gt -ge | integer comparison: equal, not equal, <, <=, >, >= |
-v name | the variable is set (even if empty) |
Logic
| Form | Where 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
| Element | Meaning |
|---|
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
| Form | What it does |
|---|
for x in a b c | over a list of words |
for f in *.log | over 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 x | over the script's arguments ("$@") |
while command / until command | while the command succeeds / while it fails |
while : / while true | infinite loop, exit with break |
break / break 2 | leave the loop / two nested loops |
continue / continue 2 | go to the next iteration of this / the outer loop |
select x in a b | a numbered menu from a list (reads stdin) |
read
| Option | What it does |
|---|
-r | don't treat \ as an escape — always use it |
IFS= read -r line | keep leading and trailing spaces of the line |
IFS=: read -r a b c | split the line on :; extra fields go into the last variable |
-a arr | the line's words go into an array |
-p 'text' | prompt before input |
-s | don't echo input (passwords) |
-n N | read exactly N characters without waiting for Enter |
-t sec | timeout; when it expires the exit code is greater than 128 |
-d char | read 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