Computer scienceSystem administration and DevOpsCommand lineBash syntax

Conditional statements and test checks

9 minutes read

Bash, like most programming languages, contains conditional statements to control the flow of execution of a program. Very often in our programs, we need to execute one block of code if a condition is true and another block if it is false. For example, if the password entered by the user is correct, then they should be taken to the next page, and if it is incorrect, an error message should appear. This kind of flow control can be achieved using conditional statements which we are going to explore in this topic.

Basic if-statement

The most common conditional statement you would encounter is the if-statement. The if-statement allows you to execute a block of code if some condition is met and to skip that block if the condition is not met.

The syntax of this basic if-statement is as follows:

if [conditions]; then
   commands
fi

These conditions are actually testing commands that get executed and give back a return status. If the return status of the test commands is 0 (success), the commands inside the if-block get executed and if the status is non-zero (failure), the commands are skipped.

Notice the semicolon after the test conditions in the above syntax. A semicolon is a must here because we are writing two different statements, the if-statement and the then-statement, on the same line.

Test command and its options

The test command is used to perform various checks/comparisons. It has two different syntaxes which are equivalent though the second syntax is far more popular.

test expression

or

[ expression ]

The test command returns a value of 0 when the expression is true and a value of 1 when the expression is false.

Note that you need to have spaces both before and after the expression.

A few commonly used options with test expressions are given below. You can find a complete list of these options on the Linux man-pages.

Test command options

Option

Purpose

Syntax

-eq

True if two integers are equal

if [ INT1 -eq INT2 ]

-ne

True if two integers are not equal

if [ INT1 -ne INT2 ]

-gt

True if the first integer is greater than the second

if [ INT1 -gt INT2 ]

-ge

True if the first integer is greater than or equal to the second

if [ INT1 -ge INT2 ]

-lt

True if the first integer is smaller than the second

if [ INT1 -lt INT2 ]

-le

True if the first integer is smaller than or equal to the second

if [ INT1 -le INT2 ]

=

True if two strings are equal

if [ STRING1 = STRING2 ]

!=

True if two strings are not equal

if [ STRING1 != STRING2 ]

\>

True if the first string is greater than the second

if [ STRING1 \> STRING2 ]

-z

True if the string is null

if [ -z STRING ]

-n

True if the string is not null

if [ -n STRING ]

-e

True if file exists

if [ -e FILE ]

-d

True if the file is a directory

if [ -d FILE ]

-s

True if the file is not empty (non-zero file size)

if [ -s FILE ]

The following logical operators can also be used with the test command:

Logical Operators

Option

Purpose

Syntax

!

Logical NOT

if [ ! EXPR ]

-a

Logical AND

if [ EXPR1 -a EXPR2 ]

-o

Logical OR

if [ EXPR1 -o EXPR2 ]

Here is a cheatsheet of various test command options.

Let's take a look at an example of the test command in action in a basic if-statement:

# Checking the password entered by user

echo "Enter password: "
read input
if [ $input = "Pass!@#" ]; then
    echo "Correct password entered"
fi

The else block

In the above password check example, if the user enters the correct password, they get a message but if they don't enter the correct password, they get no feedback. This can be confusing for the user. So how do we include the code we want to execute when the if-condition turns out to be false? We use the else block! Any code that you want to execute in case the previous conditions are false can be put inside the else block.

So our password checker code would now look like this:

if [ $input = "Pass!@#" ]; then
    echo "Correct password entered"
else
    echo "Incorrect password entered"
fi

The elif block

Very often, you will encounter situations where the branches don't just have 2 options. For example, while comparing 2 numbers, we could have 3 options:

  1. The numbers are equal

  2. The first number is greater

  3. The second number is greater

In situations like these the elif construct comes to the rescue.

num1=20;
num2=10;

if [ "$num1" -eq "$num2" ]; then
    echo "Numbers are equal"
elif [ "$num1" -gt "$num2" ]; then
    echo "First number is greater"
else
    echo "Second number is greater"
fi

The complete syntax of the if-elif-else ladder is:

if test-commands; then
    consequent-commands
elif more-test-commands; then
    more-consequents
else
    some-more-consequents
fi

The elif and else blocks are optional in the above syntax.

Conclusion

In this topic, we've explored how conditional statements work in Bash. We went through the syntax of if, if-else, and if-elif-else blocks. We've also studied the test command and the various options that can be used with it. Head over to the exercises to test how well you understood this topic!

152 learners liked this piece of theory. 5 didn't like it. What about you?
Report a typo