LLI Wiki — My Digital Knowledge Base

Bash: if conditions, test operators and case

Bash conditions cheat sheet: if/elif/else, integer, string and file operators, case, boolean operators and using a function as a condition.

This article is a quick reference for conditions in Bash and POSIX shell scripts: if / elif / else, the test operators (integer, string, file), case, boolean operators, and using a function as a condition.

if / elif / else

if [ <some test> ]
then
    <commands>
elif [ <some test> ]
then
    <different commands>
else
    <other commands>
fi

The single brackets [ ... ] are the traditional form and are equivalent to the test command. Spaces after [ and before ], and around operators, are required. The double-bracket form [[ ... ]] is more recent, offers a few advantages, but is less portable to other shells such as ksh.

if [ arg1 operator arg2 ] ; then list ; else list ; fi
if test arg1 operator arg2 ; then list
if [[ arg1 operator arg2 ]] ; then list

Each test returns true (exit code 0) when the condition is met and false (exit code 1) otherwise.

Integer comparison

Operator Description Example
-eq is equal to if [ "$a" -eq "$b" ]
-ne is not equal to if [ "$a" -ne "$b" ]
-gt is greater than if [ "$a" -gt "$b" ]
-ge is greater than or equal to if [ "$a" -ge "$b" ]
-lt is less than if [ "$a" -lt "$b" ]
-le is less than or equal to if [ "$a" -le "$b" ]
< is less than (within double parentheses) (("$a" < "$b"))
<= is less than or equal to (within double parentheses) (("$a" <= "$b"))
> is greater than (within double parentheses) (("$a" > "$b"))
>= is greater than or equal to (within double parentheses) (("$a" >= "$b"))
X=1 ; if [ $X -eq 1 ] ; then echo "X equals 1" ; else echo "X does not equal 1" ; fi

String comparison

Operator Description
= is equal to. Spaces around = are required: [ "$a"="$b" ] is not equivalent to [ "$a" = "$b" ]
== synonym for = (not POSIX); behaves differently in [[ ]] (see below)
!= is not equal to; uses pattern matching inside [[ ... ]]
< sorts before, in ASCII order: [[ "$a" < "$b" ]] or [ "$a" \< "$b" ] (must be escaped inside [ ])
> sorts after, in ASCII order: [[ "$a" > "$b" ]] or [ "$a" \> "$b" ] (must be escaped inside [ ])
-z string is null (zero length)
-n string is not null

== does not behave the same in single and double brackets:

[[ $a == z* ]]   # True if $a starts with "z" (pattern matching)
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching)

[ $a == z* ]     # File globbing and word splitting take place
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching)

Always quote variables in string tests. Example with -z:

String=''   # Zero-length ("null") string variable
if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi

To get the length of a string, expr length "$MyVar" works (the quotes are required):

MyVar="How long is this?" ; expr length "$MyVar"
17

File tests

Operator True if
-a file, -e file the file exists
-b file the file exists and is a block special file
-c file the file exists and is a character special file
-d file the file exists and is a directory
-f file the file exists and is a regular file
-g file the file exists and has the set-group-id bit
-h file, -L file the file exists and is a symbolic link
-k file the file exists and has the sticky bit
-p file the file exists and is a named pipe (FIFO)
-r file the file exists and is readable
-s file the file exists and has a size greater than zero
-t fd the file descriptor is open and refers to a terminal
-u file the file exists and has the set-user-id bit
-w file the file exists and is writable
-x file the file exists and is executable
-G file the file exists and is owned by the effective group ID
-N file the file exists and has been modified since it was last read
-O file the file exists and is owned by the effective user ID
-S file the file exists and is a socket
file1 -ef file2 both refer to the same device and inode numbers
file1 -nt file2 file1 is newer than file2, or file1 exists and file2 does not
file1 -ot file2 file1 is older than file2, or file2 exists and file1 does not

Distinguishing a missing file, an empty file and a file with data requires elif:

File="TestFile1"
if [ -s "$File" ]
then
   echo "$File exists and contains data."
elif [ -e "$File" ]
then
   echo "$File exists and is empty."
else
   echo "$File does not exist."
fi

Other operators

Operator Description
! EXPRESSION the expression is false
-o optname the shell option optname is enabled
-v varname the variable varname is set (has been assigned a value)
-R varname the variable varname is set and is a name reference

Boolean operations

Operator Meaning
&& and
|| or

case

case <variable> in
<pattern 1>)
    <commands>
    ;;
<pattern 2>)
    <other commands>
    ;;
esac

Using a function in an if statement

A function can be used as a condition through its return code:

function foo {
    if [ (your conditions) ]; then
        return 0
    else
        return 1
    fi
}

foo
if [ "$?" -eq 0 ]; then
    echo "Conditions verified"
else
    echo "Conditions NOT verified"
fi

Or through the text it prints, captured with command substitution:

function cpuname {
    echo $(grep 'model name' /proc/cpuinfo | cut -d: -f2 | tail -n1)
}

if [ "x$(cpuname)" == "xAMD Athlon" ]; then
    echo "We are running on AMD";
else
    echo "We are NOT running on AMD";
fi

The x prefix in the comparison protects against shell versions that can fail the test when one side is an empty string.

Notes

Mastodon LLIMastodon SocialFosstodon