X
Popular Searches

Conditional Testing in Bash: if, then, else, elif

Bash Shell

Programming in Bash can be fun at times. Knowing how to separate your if’s from your else-if’s or elif’s as they are called in Bash, can be fun too. Find out how get your Bash conditionals right.

Bash Conditionals: if, then, else, elif

In as good as all coding languages, there are conditionals – conditional statements which allow one to test for a variety of situations. In most programming languages, a basic if statement would allow one to test the status or value of a given programming variable. For example, one could test if a variable is empty or not.

To learn more about Bash variables, you may like to review our Bash Functions and Local Variables article.

Bash is a full-blown Linux shell, and a comprehensive programming language. It also includes many extensions to the more common conditional statements within it’s scripting/programming language. For example, one can test for the presence of files, to see if a grep -q statement was successful and so on.

Additionally, one can specify complex conditional statements, and even subshells right inside the if etc. conditional statement itself. This makes Bash very suitable for big data wrangling/mangling, text parsing and many other DevOps-like tasks.

Advertisement

This article will focus mainly on getting the conditionals right, using if...then, else, and elif statements. A future article will look at more complex test conditions, using subshells inside conditional statements etc.

Bash Conditional Testing: if..then…fi

Writing a conditional statement in Bash is easy and straightforward. You can even write them directly on the Bash command line, without using a script:

if [ "1" == "1" ]; then echo 'true'; fi

Simple if example in Bash

The outcome is true, as 1 matches 1. Note that the way to test equality between to items is to use == and not =. This is the case in many languages and is often done to avoid, or clearly separate from, “assignment” (i.e setting a variable to a given value).

Note also that we terminate each conditional if statement with a terminating fi (the reverse of if) statement. This allows us to specify multiple lines after then then clause before terminating the then section.

Bash Conditional Testing: else And Variables

Let us now put this into a little script, add an else section, and add some variable checks.

We define test.sh as follows:

#!/bin/bash

VAR1=1
VAR2=1

if [ "${VAR1}" == "${VAR2}" ]; then 
  echo 'true'
else 
  echo 'false'
fi

Then, we make this little script executable by issuing chmod +x test.sh which sets the executable flag for the test.sh script.

In-script if example using variables and an else clause

Advertisement

Inside the script we set VAR1 and VAR2 to the value of 1. We next issue an if statement which compares the two variables, and echo true if the comparison is valid, and false if the comparison failed. The result is a correct true output.

Bash Conditional Testing: if Nesting, and Advanced Checks

We can expand the last example a little further, and check for inequality using != instead of ==, add nested loops and use some Bash native advanced variable checks at the same time.

We define test2.sh as follows:

#!/bin/bash

VAR1="${1}"
VAR2="${2}"

if [ ! -z "${VAR1}" -a ! -z "${VAR2}" ]; then
  if [ "${VAR1}" != "${VAR2}" ]; then 
    echo 'true'
  else 
    echo 'false'
  fi
else
  echo "Assert: Either VAR1 (value: '${VAR1}'), or VAR2 (value: '${VAR2}'), or both, are empty!"
fi

In this script, we replaced our hard-coded values of 1 for both VAR1 and VAR2 with two special variables namely ${1} and ${2}, which stand for the first and second option/parameter, passed from the command line to the script. We make our script executable again, and execute it with various wrong option combinations.

A more complex inequality if statement which also tests script variables

The -z code stands for check if a parameter is empty or not. We negate the result (i.e. yes becomes no and no becomes yes, or rather/better true becomes false and false becomes true) by using an exclamation mark (!) in front of the -z check. We then also use an AND clause (i.e. both sides of the AND clause have to prove true).

In other words, the way that you could read the if [ ! -z "${VAR1}" -a ! -z "${VAR2}" ]; line in natural language is Both VAR1 and VAR2 should not be empty. We can see that our variables are being checked correctly by this conditional statement, as every time we try to pass only one variable, or two variables where one is empty, the program jumps to the else clause which reports on our incorrect script option usage.

Finally, inside the first if conditional statement, we have a secondary (computer jargon: nested) conditional statement. This statement does our inequality check by using not equal (!=). Sure enough, when we pass two different values namely 1 and 2 to the script, the output is true: these numbers are unequal.

Bash Conditional Testing: elif

When you start developing more complex and deeply nested statements in Bash, you will soon find that there is a case in which you are branching deeper and deeper into nested code, and the code starts looking more complex because of the multiple layers of depth. Often, though not always, one can use an elif statement in such cases. For example:

#!/bin/bash

if [ "${1}" -lt 2 ]; then
  echo "less than 2"
else
  if [ "${1}" -lt 4 ]; then
    echo "less than 4"
  else
    if [ "${1}" -lt 6 ]; then
      echo "less than 6"
    fi
  fi
fi

if [ "${1}" -lt 2 ]; then
  echo "less than 2"
elif [ "${1}" -lt 4 ]; then
  echo "less than 4"
elif [ "${1}" -lt 6 ]; then
  echo "less than 6"
fi
Advertisement

Having defined this script as test3.sh, we make it executable and run it.

elif conditional statement example with two different implementations

The two code blocks do exactly the same: they check whether the value passed as the first option to the script (1, 3 and 5 respectively) is less than (-lt) the values 2, 4 and 6 in sequence. We see that the two blocks work exactly the same.

However, the second block of code, which employs the use of elif statements (which can also be read as else if statements) instead of else..if conditional statement blocks. The second block of code is not only shorter, it is also cleaner, clearer and more easy on the eye. Note that you can also combine else and elif statements in combination, in a nested fashion etc.

Conclusion

Writing Bash code is, was and will likely for quite some time to come an enjoyable exercise for many. Creating well crafted conditional statements is an integral and commonplace part of this. In this short tutorial, we looked at if, then, else, elif and fi statements. Using the various conditional statements you will be able to create great and clean code. Enjoy!

Roel Van de Paar Roel Van de Paar
Roel has 25 years experience in IT & business, 9 years of leading teams, and 5 years in hiring & building teams. He worked for companies like Oracle, Volvo, Sun, Percona, Siemens, Karat and now MariaDB in various senior, principal, lead and managerial roles. Read Full Bio »

The above article may contain affiliate links, which help support CloudSavvy IT.