All programming languages have the ifelse conditions and they’re different in syntax according to each programming languages. In Bash, it’s really different and even a small space can cause syntax errors. So, you have to be careful while writing Bash code.

In this post, I’ll give you many examples on how to use if and else conditions in Bash.

if, else

a="AC"
if [ $a = "AC" ]; then
	echo "yes"
else
	echo "no"
fi

Notice the usage of then. It’s necessary to let Bash know that if the condition returns TRUE, do the code below it.

The if condition is closed by fi. It’s the way of using “}” to close the condition in other languages and then, the way of starting “{” in other languages.

But, else doesn’t have special closing command; the fi will do. Unlike “==” in other languages, in Bash just an “=” will do to check if a variable contain a string.

The space between “[” is really necessary. If you remove it, syntax errors like these will occur :

file.sh: line 2: [AC: command not found
file.sh: line 2: syntax error near unexpected token `then'
file.sh: line 2: `if[ $a = "a" ]; then

Examples

Check if the variable “a” doesn’t have the value “AC” :

a="a"
if [ ! $a = "AC" ]; then
    echo "yes, a is not 'AC'"
fi

Check if the file “/dev/null” exist :

if [ -a /dev/null ]; then
    echo "File Exists"
else
    echo "File doesn't exist"
fi

Check if the directory “/dev” exist :

if [ -d /dev ]; then
    echo "Directory Exists"
else
    echo "Directory doesn't exist"
fi

elif

This command elif is the same as else if used in other programming languages. It should be used after if and before fi.

a="AC"
if [ $a = "a" ]; then
    echo "it's 'a'"
elif [ $a = "AC" ]; then
    echo "it's 'AC'"
fi

The else command also can be used within this :

a="k"
if [ $a = "a" ]; then
    echo "it's 'a'"
elif [ $a = "AC" ]; then
    echo "it's 'AC'"
else
    echo "it's none of it"
fi

Examples

Check if variable “a” contains “a”, else check if the value is “false” :

a=false
if [ $a = "a" ]; then
    echo "it's 'a'"
elif [ $a = false ]; then
    echo "it's FALSE"
fi

Check if the value of variable “a” is greater than or less than 51 :

a=50
if [ $a -gt 51 ]; then
    echo "it's more than 50"
elif [ $a -lt 51 ]; then
    echo "it's less than 51"
fi