Conditions and tests
Scripts need to make decisions: does this file exist? did the build pass? is the disk nearly full? In Bash, every decision is based on a command's exit code: 0 counts as true, anything else as false.
if
if grep -q "^you:" /etc/passwd; then
echo "user 'you' exists"
fi
if ping -c1 -W1 no-such-host.invalid > /dev/null 2>&1; then
echo "host is up"
else
echo "host is unreachable"
fiuser 'you' exists host is unreachable
The shape is always if COMMAND; then … elif COMMAND; then … else … fi. Any command works as the condition, which is why if grep -q … and if mkdir dir are so common.
[[ ]]: testing values
To compare strings and numbers or check files, use the test command [[ … ]]. It succeeds or fails like any other command:
name="asha"
age=31
if [[ $name == "asha" ]]; then echo "hello asha"; fi
if [[ $age -ge 18 ]]; then echo "adult"; fi
if [[ -z $missing ]]; then echo "missing is empty"; fi
[[ 5 -lt 3 ]]
echo "5 -lt 3 → exit code $?"hello asha adult missing is empty 5 -lt 3 → exit code 1
The spaces inside [[ and ]] are required: [[$age -ge 18]] is an error.
String tests
| Test | True when |
|---|---|
[[ $a == $b ]] |
Equal (the right side can be a glob: [[ $f == *.log ]]) |
[[ $a != $b ]] |
Not equal |
[[ $a =~ regex ]] |
Matches a regular expression |
[[ -z $a ]] |
Empty |
[[ -n $a ]] |
Not empty |
Number tests
| Test | Meaning |
|---|---|
-eq -ne |
equal, not equal |
-lt -le |
less than, less or equal |
-gt -ge |
greater than, greater or equal |
Or use arithmetic (( )), which reads like other languages:
disk=91
if (( disk > 90 )); then
echo "CRITICAL: disk at ${disk}%"
elif (( disk > 75 )); then
echo "warning: disk at ${disk}%"
else
echo "ok"
fiCRITICAL: disk at 91%
⚠️ Inside
[[ ]],<and>compare text, alphabetically:[[ 10 < 9 ]]is true, because "1" sorts before "9". Use-ltor(( ))for numbers.
File tests
| Test | True when the path… |
|---|---|
-e path |
exists |
-f path |
is a regular file |
-d path |
is a directory |
-s path |
is a file and not empty |
-r -w -x path |
is readable, writable, executable by you |
-L path |
is a symbolic link |
a -nt b |
a is newer than b |
config=/etc/hostname
if [[ -f $config ]]; then
echo "$config exists ($(wc -c < "$config") bytes)"
fi
[[ -d /var/log ]] && echo "/var/log is a directory"
[[ -w /etc/passwd ]] || echo "you can't write /etc/passwd (good!)"
mkdir -p ~/backups
[[ -x ~/backups ]] && echo "you can enter ~/backups"/etc/hostname exists (7 bytes) /var/log is a directory you can't write /etc/passwd (good!) you can enter ~/backups
Combining conditions
user="admin"
port=8080
if [[ $user == "admin" && $port -gt 1024 ]]; then echo "both true"; fi
if [[ $user == "root" || $port -eq 8080 ]]; then echo "at least one true"; fi
if [[ ! -e /tmp/lock ]]; then echo "no lock file"; fi
if grep -q you /etc/passwd && [[ -d /home/you ]]; then echo "user and home exist"; fiboth true at least one true no lock file user and home exist
Inside [[ ]] use &&, || and !. Between commands, && and || chain them as you saw in the first lesson.
Pattern and regex matching
for file in report.pdf photo.JPG notes.txt; do
if [[ $file == *.pdf ]]; then
echo "$file: PDF"
elif [[ ${file,,} == *.jpg ]]; then
echo "$file: image"
else
echo "$file: other"
fi
done
email="asha@example.com"
if [[ $email =~ ^[^@]+@([^@]+)$ ]]; then
echo "valid, domain is ${BASH_REMATCH[1]}"
fi
version="v2.14.3"
if [[ $version =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
echo "major ${BASH_REMATCH[1]}, minor ${BASH_REMATCH[2]}, patch ${BASH_REMATCH[3]}"
fireport.pdf: PDF photo.JPG: image notes.txt: other valid, domain is example.com major 2, minor 14, patch 3
=~ stores the regex groups in the array BASH_REMATCH. Don't put quotes around the regex: quoted, it's matched as plain text.
[[ ]] vs [ ] vs test
You'll see three spellings:
[ … ]andtest …are the old POSIX commands. They work in every shell (shtoo), but unquoted variables inside them break on spaces and empty values.[[ … ]]is Bash's improved version: no word splitting inside,&&/||, patterns and=~.
empty=""
[ $empty = "x" ] && echo yes
echo "single brackets: exit $?"
[[ $empty = "x" ]] && echo yes
echo "double brackets: exit $?"bash: [: =: unary operator expected single brackets: exit 2 double brackets: exit 1
The [ ] version became [ = "x" ], which isn't a valid test. Use [[ ]] in Bash scripts and [ "$var" = x ] (quoted!) in sh scripts.
case: many choices
When one value can be one of several things, case is cleaner than a chain of elifs. It's the standard way to handle sub-commands like start/stop:
#!/usr/bin/env bash
case "$1" in
start)
echo "starting the app" ;;
stop|halt)
echo "stopping the app" ;;
restart)
echo "stopping the app"
echo "starting the app" ;;
*.conf)
echo "loading config file $1" ;;
"")
echo "usage: $0 {start|stop|restart|FILE.conf}" >&2
exit 1 ;;
*)
echo "unknown command: $1" >&2
exit 1 ;;
esacbash service.sh start
bash service.sh halt
bash service.sh prod.conf
bash service.sh dance
bash service.shstarting the app
stopping the app
loading config file prod.conf
unknown command: dance
usage: service.sh {start|stop|restart|FILE.conf}Each choice is a glob pattern (| means "or"), ends with ), and its commands end with ;;. *) catches everything else. The block closes with esac (case backwards, like fi).
Asking for confirmation
A safety check every destructive script should have:
#!/usr/bin/env bash
read -rp "Delete all logs in /tmp/app? [y/N] " answer
if [[ ${answer,,} == y || ${answer,,} == yes ]]; then
echo "deleting…"
else
echo "cancelled"
fibash cleanup.shDelete all logs in /tmp/app? [y/N] n cancelled
The capital N in [y/N] is a convention: it's what happens if you just press Enter.
Practice
- Write
age.shthat takes an age as$1and printschild(under 13),teen(13–19) oradult. Print a usage message if no age is given. - Write
check-file.sh PATHthat says whether the path is a file, a directory, or doesn't exist, and whether you can write to it. - Use
caseto print the type of a file from its extension: images (jpg|png|gif), documents (pdf|docx), orother. - Use
=~to check that$1looks like a dateYYYY-MM-DD.
1.In Bash, which exit code counts as "true" in an if?
2.What's wrong with if [[$x -gt 5]]; then?
3.Which test is true when a directory exists?
4.How do you compare numbers correctly?