ZetCode

Bash Conditionals and the test Command

last modified October 24, 2026

Conditionals let a script choose what to do: run a command only if a file exists, report an error if an argument is missing, or handle each kind of input differently. Bash decides with exit statuses: a condition is true when a command succeeds (status 0). The test command and its forms [ ] and [[ ]] check files, strings, and numbers; (( )) evaluates arithmetic; and case matches patterns.

The examples were run with Bash 5.2 on Debian 12. A working directory contains a logs directory with an application log, an empty file, an executable script, and two symbolic links, one of them broken.

The if statement

if runs a command and executes the then branch if the command succeeds. Any command can serve as the condition.

if grep -q ERROR logs/app.log; then
    echo "errors found"
fi

if grep -q WARNING logs/app.log; then
    echo "warnings found"
else
    echo "no warnings"
fi

grep -q prints nothing and only sets its exit status: 0 if the pattern was found, 1 if not. The else branch runs when the condition fails. In the transcripts, the > at the start of a line is the shell's prompt for the continuation of a command that spans several lines.

$ if grep -q ERROR logs/app.log; then
>     echo "errors found"
> fi
errors found
$ if grep -q WARNING logs/app.log; then
>     echo "warnings found"
> else
>     echo "no warnings"
> fi
no warnings

The test command and [ ]

To check conditions that are not commands, such as whether a file exists, we use test. The [ command is another name for test that requires a closing ].

test -d logs; echo $?
[ -d logs ]; echo $?
[ -d nosuchdir ]; echo $?
type [ test
ls -l /usr/bin/[

-d tests for a directory. Both forms return 0 (true) or 1 (false). [ is not shell syntax but a command, built into Bash and also available as a program in /usr/bin. This explains its strict rules about spaces.

$ test -d logs; echo $?
0
$ [ -d logs ]; echo $?
0
$ [ -d nosuchdir ]; echo $?
1
$ type [ test
[ is a shell builtin
test is a shell builtin
$ ls -l /usr/bin/[
-rwxr-xr-x 1 root root 68496 Sep 20  2022 /usr/bin/[

Spaces matter

Because [ is a command, it must be separated from its arguments by spaces, and ] must be a separate last argument.

[-d logs]
[ -d logs]
[ -d logs ] && echo "logs is a directory"

Without the space, Bash looks for a command named [-d. In the second line, the last argument is logs], so [ misses its closing bracket. The third form is correct; && runs the echo only if the test succeeds.

$ [-d logs]
bash: [-d: command not found
$ [ -d logs]
bash: [: missing `]'
$ [ -d logs ] && echo "logs is a directory"
logs is a directory

File tests

The most common tests check files. The loop below applies six of them to several paths and prints those that are true.

ls -l logs/app.log empty.txt start.sh current.log broken.log
for f in logs logs/app.log empty.txt start.sh current.log broken.log nofile; do
    printf '%-13s' "$f"
    for t in -e -f -d -L -s -x; do
        if [ $t "$f" ]; then printf ' %s' "$t"; else printf '   '; fi
    done
    echo
done

-e means the path exists, -f a regular file, -d a directory, -L a symbolic link, -s a size greater than zero, and -x executable (for a directory, searchable). The tests follow symbolic links, except -L: current.log passes -f, because its target is a regular file, while the broken link passes only -L; -e is false for it, since its target does not exist.

$ ls -l logs/app.log empty.txt start.sh current.log broken.log
lrwxrwxrwx 1 jano jano 11 Oct 24 21:54 broken.log -> missing.txt
lrwxrwxrwx 1 jano jano 12 Oct 24 21:54 current.log -> logs/app.log
-rw-r--r-- 1 jano jano  0 Oct 24 21:54 empty.txt
-rw-r--r-- 1 jano jano 32 Oct 24 21:54 logs/app.log
-rwxr-xr-x 1 jano jano  8 Oct 24 21:54 start.sh
$ for f in logs logs/app.log empty.txt start.sh current.log broken.log nofile; do
>     printf '%-13s' "$f"
>     for t in -e -f -d -L -s -x; do
>         if [ $t "$f" ]; then printf ' %s' "$t"; else printf '   '; fi
>     done
>     echo
> done
logs          -e    -d    -s -x
logs/app.log  -e -f       -s
empty.txt     -e -f
start.sh      -e -f       -s -x
current.log   -e -f    -L -s
broken.log             -L
nofile

More file tests and negation

Other tests compare files or check permissions, and ! negates a test.

touch -d '2026-10-01' old.txt; touch new.txt
[ new.txt -nt old.txt ] && echo "new.txt is newer"
[ -r /etc/shadow ] || echo "cannot read /etc/shadow"
[ ! -e config.ini ] && echo "config.ini does not exist"

-nt (newer than) and -ot (older than) compare modification times. -r, -w, and -x check whether the current user may read, write, or execute a file. || runs the following command if the test fails.

$ touch -d '2026-10-01' old.txt; touch new.txt
$ [ new.txt -nt old.txt ] && echo "new.txt is newer"
new.txt is newer
$ [ -r /etc/shadow ] || echo "cannot read /etc/shadow"
cannot read /etc/shadow
$ [ ! -e config.ini ] && echo "config.ini does not exist"
config.ini does not exist

String tests

Strings are compared with = and !=; -z tests for an empty string and -n for a non-empty one.

name="Jan"
[ "$name" = "Jan" ] && echo equal
[ "$name" != "Peter" ] && echo "not Peter"
empty=""
[ -z "$empty" ] && echo "empty is empty"
[ -n "$name" ] && echo "name is not empty"

Inside [ ], use a single = for comparison; == works in Bash but not in other shells. Variables are quoted, for the reason shown in the next section.

$ name="Jan"
$ [ "$name" = "Jan" ] && echo equal
equal
$ [ "$name" != "Peter" ] && echo "not Peter"
not Peter
$ empty=""
$ [ -z "$empty" ] && echo "empty is empty"
empty is empty
$ [ -n "$name" ] && echo "name is not empty"
name is not empty

Always quote variables in [ ]

[ receives its arguments after the shell has expanded them. An unquoted variable that is empty disappears, and one that contains spaces becomes several arguments.

answer=""
[ $answer = yes ] && echo confirmed
answer="no thanks"
[ $answer = yes ] && echo confirmed
[ "$answer" = yes ] || echo "not confirmed"

With the empty variable, the command becomes [ = yes ], and [ complains that = needs an operand on the left. With no thanks, it becomes [ no thanks = yes ], which has too many arguments. Quoted, the variable is always exactly one argument. See the Bash quoting article for more.

$ answer=""
$ [ $answer = yes ] && echo confirmed
bash: [: =: unary operator expected
$ answer="no thanks"
$ [ $answer = yes ] && echo confirmed
bash: [: too many arguments
$ [ "$answer" = yes ] || echo "not confirmed"
not confirmed

Comparing numbers

Numbers are compared with -eq (equal), -ne (not equal), -lt (less than), -le (less or equal), -gt (greater than), and -ge (greater or equal).

count=15
[ "$count" -gt 10 ] && echo "more than ten"
[ "$count" -le 20 ] && echo "at most twenty"
[ "$count" -eq 15.0 ]
[ "abc" -eq 1 ]

The operators work only with integers. Bash has no floating-point arithmetic; use awk or bc to compare decimal numbers.

$ count=15
$ [ "$count" -gt 10 ] && echo "more than ten"
more than ten
$ [ "$count" -le 20 ] && echo "at most twenty"
at most twenty
$ [ "$count" -eq 15.0 ]
bash: [: 15.0: integer expression expected
$ [ "abc" -eq 1 ]
bash: [: abc: integer expression expected

The > trap

Inside [ ], > and < are redirections, not comparisons.

[ 10 > 9 ] && echo "10 is greater"
ls -l 9
[ 2 > 10 ] && echo "2 is greater?"
rm 9 10
[ 2 -gt 10 ] || echo "2 is not greater"

[ 10 > 9 ] runs [ 10 ] with its output redirected to a new file named 9. [ 10 ] tests whether the string 10 is non-empty, which is true, so the comparison seems to work, until [ 2 > 10 ] is true as well. For numbers, use -gt and friends.

$ [ 10 > 9 ] && echo "10 is greater"
10 is greater
$ ls -l 9
-rw-r--r-- 1 jano jano 0 Oct 24 21:54 9
$ [ 2 > 10 ] && echo "2 is greater?"
2 is greater?
$ rm 9 10
$ [ 2 -gt 10 ] || echo "2 is not greater"
2 is not greater

The [[ ]] command

Bash, Zsh, and Ksh have a more convenient test syntax, [[ ]]. It is part of the shell's grammar, so variables inside are not split into words, and < and > are comparisons.

file="my notes.txt"
[ -e $file ] || echo "not found"
[[ -e $file ]] || echo "not found"
answer=""
[[ $answer = yes ]] || echo "not confirmed"
[[ 10 > 9 ]] || echo "false: 10 and 9 are compared as strings"
[[ 10 -gt 9 ]] && echo "true: compared as numbers"
[[ abc < abd ]] && echo "abc sorts before abd"

The unquoted file name with a space breaks [ ] but works in [[ ]], and so does the empty variable. Note that < and > compare strings in sort order: 10 sorts before 9, because the character 1 comes before 9. Numbers still need -gt or arithmetic. In Bash scripts, [[ ]] is the safer choice; [ ] is needed only for scripts that must run in sh.

$ file="my notes.txt"
$ [ -e $file ] || echo "not found"
bash: [: my: binary operator expected
not found
$ [[ -e $file ]] || echo "not found"
not found
$ answer=""
$ [[ $answer = yes ]] || echo "not confirmed"
not confirmed
$ [[ 10 > 9 ]] || echo "false: 10 and 9 are compared as strings"
false: 10 and 9 are compared as strings
$ [[ 10 -gt 9 ]] && echo "true: compared as numbers"
true: compared as numbers
$ [[ abc < abd ]] && echo "abc sorts before abd"
abc sorts before abd

Pattern matching

On the right side of == and !=, [[ ]] treats an unquoted string as a glob pattern.

f="report-2026.pdf"
[[ $f == *.pdf ]] && echo "a PDF file"
[[ $f == report-* ]] && echo "a report"
[[ $f == "*.pdf" ]] || echo "not literally *.pdf"
[ "$f" == *.pdf ] || echo "[ does not match patterns"

* matches any string, ? one character, and [...] one of the listed characters. Quoting the pattern makes it a literal string. [ ] has no pattern matching; the *.pdf there was even subject to file name expansion.

$ f="report-2026.pdf"
$ [[ $f == *.pdf ]] && echo "a PDF file"
a PDF file
$ [[ $f == report-* ]] && echo "a report"
a report
$ [[ $f == "*.pdf" ]] || echo "not literally *.pdf"
not literally *.pdf
$ [ "$f" == *.pdf ] || echo "[ does not match patterns"
[ does not match patterns

Regular expressions

The =~ operator matches an extended regular expression. Parenthesized groups are stored in the BASH_REMATCH array.

date_str="2026-10-24"
if [[ $date_str =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
    echo "year ${BASH_REMATCH[1]}, month ${BASH_REMATCH[2]}, day ${BASH_REMATCH[3]}"
fi
email="jan@example.com"
re='^[^@ ]+@[^@ ]+\.[a-z]+$'
[[ $email =~ $re ]] && echo "looks like an email"
[[ $email =~ "$re" ]] || echo "quoted: matched literally, no match"

BASH_REMATCH[0] holds the whole match and the following elements the groups. Complex expressions are best stored in a variable and used unquoted: quoted, the expression is matched as a literal string.

$ date_str="2026-10-24"
$ if [[ $date_str =~ ^([0-9]{4})-([0-9]{2})-([0-9]{2})$ ]]; then
>     echo "year ${BASH_REMATCH[1]}, month ${BASH_REMATCH[2]}, day ${BASH_REMATCH[3]}"
> fi
year 2026, month 10, day 24
$ email="jan@example.com"
$ re='^[^@ ]+@[^@ ]+\.[a-z]+$'
$ [[ $email =~ $re ]] && echo "looks like an email"
looks like an email
$ [[ $email =~ "$re" ]] || echo "quoted: matched literally, no match"
quoted: matched literally, no match

Arithmetic conditions

(( )) evaluates an arithmetic expression with the usual operators and returns true if the result is not zero.

count=15
(( count > 10 )) && echo "more than ten"
(( count % 2 == 1 )) && echo "odd"
(( 0 )); echo $?
(( 5 )); echo $?
n=0
(( n )) || echo "n is zero"

Inside (( )), variables need no $, and >, ==, %, && work as in C. A result of 0 gives the exit status 1, any other value the status 0, the opposite of the numbers themselves. For numeric comparisons in Bash, (( )) is the most readable form.

$ count=15
$ (( count > 10 )) && echo "more than ten"
more than ten
$ (( count % 2 == 1 )) && echo "odd"
odd
$ (( 0 )); echo $?
1
$ (( 5 )); echo $?
0
$ n=0
$ (( n )) || echo "n is zero"
n is zero

Combining conditions

Conditions are combined with && (and), || (or), and ! (not).

age=25; member=yes
[[ $age -ge 18 && $member == yes ]] && echo "access granted"
[ "$age" -ge 18 ] && [ "$member" = yes ] && echo "access granted"
[[ ! -e config.ini ]] && echo "no config"
[ "$age" -ge 18 -a "$member" = yes ] && echo "works, but -a is obsolete"

Inside [[ ]], && and || can be used directly, with parentheses for grouping. With [ ], combine separate tests with the shell's && and ||. The -a and -o operators of test still work, but POSIX marks them obsolescent because they are ambiguous in some cases.

$ age=25; member=yes
$ [[ $age -ge 18 && $member == yes ]] && echo "access granted"
access granted
$ [ "$age" -ge 18 ] && [ "$member" = yes ] && echo "access granted"
access granted
$ [[ ! -e config.ini ]] && echo "no config"
no config
$ [ "$age" -ge 18 -a "$member" = yes ] && echo "works, but -a is obsolete"
works, but -a is obsolete

elif chains

elif adds further conditions; the first one that is true wins. The following script converts a score to a grade.

grade.sh
#!/bin/bash

score=$1

if ! [[ $score =~ ^[0-9]+$ ]]; then
    echo "invalid score: $score" >&2
    exit 1
elif (( score >= 90 )); then
    grade=A
elif (( score >= 80 )); then
    grade=B
elif (( score >= 70 )); then
    grade=C
else
    grade=F
fi

echo "$score: $grade"

The first condition rejects input that is not a whole number; without it, (( )) would treat abc as a variable name with the value 0. if ! negates the exit status of the following command. Error messages go to standard error, and the script exits with 1.

$ for s in 95 82 71 40 abc; do bash grade.sh $s; done
95: A
82: B
71: C
40: F
invalid score: abc

The case statement

case compares one value against a list of patterns. It is clearer than a long elif chain when the decisions are based on the form of a string.

filetype.sh
#!/bin/bash

for f in "$@"; do
    case ${f,,} in
        *.jpg | *.jpeg | *.png)  echo "$f: image" ;;
        *.txt | *.md)            echo "$f: text" ;;
        *.tar.gz | *.tgz | *.zip) echo "$f: archive" ;;
        *.sh)                    echo "$f: shell script" ;;
        *)                       echo "$f: unknown" ;;
    esac
done

Each branch ends with ;;, and | separates alternative patterns. The patterns are tried in order, and * catches everything else. ${f,,} converts the name to lowercase, so photo.JPG matches *.jpg. A file without an extension, such as Makefile, falls through to the default branch.

$ bash filetype.sh photo.JPG notes.txt archive.tar.gz script.sh Makefile
photo.JPG: image
notes.txt: text
archive.tar.gz: archive
script.sh: shell script
Makefile: unknown

Handling user answers

case with bracket patterns is a common way to process yes/no answers.

confirm.sh
#!/bin/bash

while true; do
    read -r -p "Delete all files? [y/n] " answer
    case $answer in
        [Yy] | [Yy][Ee][Ss]) echo "deleting..."; break ;;
        [Nn] | [Nn][Oo])     echo "cancelled"; break ;;
        *)                   echo "please answer y or n" ;;
    esac
done

[Yy] matches one character, so the patterns accept y, Y, yes, YES, and other mixes of case. The loop repeats the question until a valid answer is given; break leaves it. The answers were typed in a terminal.

$ bash confirm.sh
Delete all files? [y/n] y
deleting...
$ bash confirm.sh
Delete all files? [y/n] No
cancelled
$ bash confirm.sh
Delete all files? [y/n] maybe
please answer y or n
Delete all files? [y/n] yes
deleting...

Testing commands directly

Since if works with any command, there is no need to check $? separately.

if mkdir data 2> /dev/null; then
    echo "created data"
else
    echo "could not create data"
fi
mkdir data 2> /dev/null; if [ $? -ne 0 ]; then echo "could not create data"; fi
[ -d backup ] || mkdir backup
ls -d backup

The first and second forms do the same, but the first is shorter and cannot accidentally test the status of a different command. [ -d backup ] || mkdir backup is a common one-line idiom: create the directory unless it exists (mkdir -p does the same in this case).

$ if mkdir data 2> /dev/null; then
>     echo "created data"
> else
>     echo "could not create data"
> fi
could not create data
$ mkdir data 2> /dev/null; if [ $? -ne 0 ]; then echo "could not create data"; fi
could not create data
$ [ -d backup ] || mkdir backup
$ ls -d backup
backup

Validating script arguments

Scripts should check their arguments before doing any work. The following backup script checks the number of arguments and both directories.

backup.sh
#!/bin/bash

# usage: backup.sh SOURCE_DIR TARGET_DIR
if [ $# -ne 2 ]; then
    echo "usage: $0 SOURCE_DIR TARGET_DIR" >&2
    exit 2
fi

src=$1
dest=$2

if [ ! -d "$src" ]; then
    echo "error: $src is not a directory" >&2
    exit 1
fi

if [ ! -d "$dest" ] || [ ! -w "$dest" ]; then
    echo "error: cannot write to $dest" >&2
    exit 1
fi

archive="$dest/$(basename "$src")-$(date +%F).tar.gz"
tar -czf "$archive" "$src" && echo "created $archive"

$# is the number of arguments. The script prints a usage message and exits with 2, the conventional status for wrong usage, and with 1 for other errors. Only when all checks pass does it create the archive. Each failing call stops at the first problem.

$ bash backup.sh
usage: backup.sh SOURCE_DIR TARGET_DIR
$ bash backup.sh nosuchdir /tmp
error: nosuchdir is not a directory
$ bash backup.sh logs /nonexistent
error: cannot write to /nonexistent
$ bash backup.sh logs backup
created backup/logs-2026-10-24.tar.gz
$ ls backup
logs-2026-10-24.tar.gz

Testing whether a variable is set

An empty variable and an unset variable are different things. -v tests whether a variable is set.

unset color; empty=""
[[ -v color ]] || echo "color is not set"
[[ -v empty ]] && echo "empty is set"
[ -z "${color+x}" ] && echo "color is not set (portable)"

-v takes the variable's name, without $. The expansion ${color+x} gives x if the variable is set (even to an empty string) and nothing otherwise, which works in any POSIX shell. See the shell expansion article for more such forms.

$ unset color; empty=""
$ [[ -v color ]] || echo "color is not set"
color is not set
$ [[ -v empty ]] && echo "empty is set"
empty is set
$ [ -z "${color+x}" ] && echo "color is not set (portable)"
color is not set (portable)

Summary of test forms

FormUse forNotes
if commandSuccess of any commandChecks the exit status
[ ... ], testFiles, strings, integersPOSIX; quote variables; no patterns
[[ ... ]]Files, strings, patterns, regexesBash, Zsh, Ksh; no word splitting
(( ... ))Integer arithmeticC-like operators; no $ needed
caseMatching one value against patternsPOSIX; clearer than many elif

Best practices

Source

Bash manual: Conditional Constructs, Bash manual: Bash Conditional Expressions

In this article, we have written conditions with if, test, [ ], [[ ]], (( )), and case, tested files, strings, and numbers, matched patterns and regular expressions, and validated script arguments. See also the Bash loops, exit codes, and Bash quoting articles.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Linux tutorials.