How to use if, else, then, elif statements in a BASH script

Home > Search > How-to
  by

In bash, an if statement has the following structure.

if [ comparison ]; then
  --do something--
elif [ comparison ]
  --do something
else
  --do something--
fi

 

For example.

if [ $foo -eq 1 ]; then
  echo "Foo equals 1"

elif [ $foo -eq 2 ]
  echo "Foo equals 2"

else
  echo "Foo does not equal 1 or 2"

fi

 

The following table contains commonly used comparison operators.

Equals (integers) if [ $foo -eq 1 ]
Does not equal (integers) if [ $foo -ne 1 ]
Equals (strings) if [ $foo == "Hello" ]
Does not equal (strings) if [ $foo != "Hello" ]
Greater than if [ $foo -gt 1 ]
Greater than or equal to  if [ $foo -ge 1 ]
Less than if [ $foo -lt 1 ]
Less than or equal to if [ $foo -le 1 ]
Is null (empty) if [ -z $foo ]
File exists if [ -e /path/to/file ]
File does not exist if [ ! -e /path/to/file ]
Directory exists if [ -d /home/test ]
Directory does not exist if [ ! -d /home/test ]
Directory empty if [ -z "$(ls -A /path/to/directory)" ]
Directory not empty if [ ! -z "$(ls -A /path/to/directory)" ]
File contains if grep -q "Hello World" /path/to/file;
File does not contain if ! grep -q "Hello World" /path/to/file;
Variable contains if [[ $foo = *Hello* ]] 
Variable does not contain if [[ $foo != *Hello* ]] 
Variable begins with if [[ $foo =~ ^Hello ]]
Variable does not begin with if [[ ! $foo =~ ^Hello ]]
Variable ends with if [[ $foo =~ Hello$ ]]
Variable does not end with if [[ ! $foo =~ Hello$ ]]

 


Spacing

Many if statements requre a single white space inside of the brackets.

 


And (&&), Or (||)

Double && characters can be used to link statements together as an and.

if [ $foo -eq 1 ] && [ $bar -eq 1 ]
if [[ $foo == "Hello" && $bar == "World" ]]

 

Double || characters can be used to link statements together as an or.

if [ $foo -eq 1 ] || [ $bar -eq 1 ]
if [[ $foo == "Hello" || $bar == "World" ]]

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments