Understanding Bash If…Else Statements

Conditional statements are a core concept in any programming language, and Bash is no exception. In shell scripting, decision-making lets you control the flow of execution based on whether a condition is true or false. Bash provides several options for this: if, if…else, if…elif…else, and nested if statements.

In this guide, we’ll walk through the basics of the Bash if…else statement, explain how it works, and demonstrate its usage with practical examples.

The Basic If Statement

There are different forms of Bash if conditional statements. The simplest form of conditional execution in Bash looks like this:

if TEST-COMMAND
then
  STATEMENTS
fi

The if statement in Bash begins with the if keyword, followed by a conditional expression, and then the then keyword. The statement is closed using the fi keyword (which is simply “if” spelled backward).

if [ TEST-COMMAND ]; then
    STATEMENTS
fi

If the TEST-COMMAND evaluates to True, the STATEMENTS inside the block are executed. If the TEST-COMMAND returns False, nothing happens — the commands inside the block are skipped.

Example: Check if a Number is Greater than 10

#!/bin/bash
echo -n "Enter a number: "
read VAR
if [[ $VAR -gt 10 ]]
then
  echo "The variable is greater than 10."
fi

You need to save the code in a file and have to run it from the command line. For example, if you save the code in a file as: bash samplecode.sh and when executed, the script will ask to enter a number. You need to enter 15, the output will be:

The variable is greater than 10.

If…Else Statement

The following is the form of the Bash if…else statement:

if TEST-COMMAND
then
  STATEMENTS1
else
 STATEMENTS2
fi

If the TEST-COMMAND evaluates to True, the STATEMENTS1 will be executed. Otherwise, if TEST-COMMAND returns False, the STATEMENTS2 will be executed. You can have only one else clause in the statement.

Example:

#!/bin/bash
echo -n "Enter a number: "
read VAR
if [[ $VAR -gt 10 ]]
then
  echo "The variable is greater than 10."
else
  echo "The variable is equal to or less than 10."
fi

When you run the code above, it prompts you to enter a number. Now, the script will display an output based on whether the number is greater than, less than, or equal to 10.

If…Elif…Else Statement

When you need to check multiple conditions, you can use elif. The following is the form of the Bash if…elif…else statement:

if TEST-COMMAND1
then
  STATEMENTS1
elif TEST-COMMAND2
then
  STATEMENTS2
else
  STATEMENTS3
fi

If TEST-COMMAND1 evaluates to True, the STATEMENTS1 block is executed. (OR)
If TEST-COMMAND2 evaluates to True, then STATEMENTS2 will be executed instead.
If none of the test commands evaluate to True, the STATEMENTS3 block (inside the else clause) will run.

You can include one or more elif clauses between the if and else sections, depending on how many conditions you want to check. The else clause itself is optional.

Each condition is evaluated in order, from top to bottom. As soon as one condition evaluates to True, the remaining conditions are skipped, and the script continues executing after the entire if block.

Example:

#!/bin/bash
echo -n "Enter a number: "
read VAR
if [[ $VAR -gt 10 ]]
then
  echo "The variable is greater than 10."
elif [[ $VAR -eq 10 ]]
then
  echo "The variable is equal to 10."
else
  echo "The variable is less than 10."
fi

Nested If Statements

Bash also allows you to place if statements inside other if statements. While powerful, they can quickly become messy, so use them carefully.

Below is a script that will ask you to enter three numbers and, based on the input it print the largest number among those three numbers.

Example: Find the Largest of Three Numbers

#!/bin/bash
echo -n "Enter the first number: "
read VAR1
echo -n "Enter the second number: "
read VAR2
echo -n "Enter the third number: "
read VAR3
if [[ $VAR1 -ge $VAR2 ]]
then
  if [[ $VAR1 -ge $VAR3 ]]
  then
    echo "$VAR1 is the largest number."
  else
    echo "$VAR3 is the largest number."
  fi
else
  if [[ $VAR2 -ge $VAR3 ]]
  then
    echo "$VAR2 is the largest number."
  else
    echo "$VAR3 is the largest number."
  fi
fi

Sample Output:
Once the above code is executed, the output will look like:

Enter the first number: 8
Enter the second number: 4
Enter the third number: 1

8 is the largest number.

Tip: For complex conditions, consider using the case statement instead—it is recommended.

Using Multiple Conditions

The logical OR and logical AND operators enable you to combine multiple conditions within an if statement.

You can combine conditions using logical operators:

  • && (AND): all conditions must be true.
  • || (OR): at least one condition must be true.

Here’s an updated version of the script that determines the largest number among three values. In this approach, instead of using nested if statements, we utilize the logical AND (&&) operator to make the code more concise and easier to read.

Example with AND Operator:

#!/bin/bash
echo -n "Enter the first number: "
read VAR1
echo -n "Enter the second number: "
read VAR2
echo -n "Enter the third number: "
read VAR3
if [[ $VAR1 -ge $VAR2 ]] && [[ $VAR1 -ge $VAR3 ]]
then
  echo "$VAR1 is the largest number."
elif [[ $VAR2 -ge $VAR1 ]] && [[ $VAR2 -ge $VAR3 ]]
then
  echo "$VAR2 is the largest number."
else
  echo "$VAR3 is the largest number."
fi

Sample Output:
Once the above code is executed, the output will look like:

Enter the first number: 8
Enter the second number: 4
Enter the third number: 1

8 is the largest number.

Test Operators in Bash

In Bash, the test command can be written in any of the following forms:

test EXPRESSION
[ EXPRESSION ]
[[ EXPRESSION ]]

To ensure your script is portable, it’s best to use the traditional test or [ … ] syntax, as these are supported by all POSIX-compliant shells.

The newer [[ … ]] syntax is an enhanced version of test, offering additional features and improved syntax handling. It is supported by most modern shells such as Bash, Zsh, and Ksh.

To negate a test expression, use the logical NOT (!) operator. When comparing strings, always enclose them in single or double quotes to prevent issues with word splitting or globbing.

The test command (or its shorthand [ ] and [[ ]]) evaluates conditions. Here are some common operators:

String Operators

  • -n VAR → Returns true if the variable VAR is not empty
  • -z VAR → Returns true if the variable VAR is empty
  • STRING1 = STRING2 → Returns true if both strings are equal
  • STRING1 != STRING2 → Returns true if the strings are different

Integer Operators

  • -eq → Equal to
  • -ne → Not equal to
  • -gt → Greater than
  • -lt → Less than
  • -ge → Greater than or equal to
  • -le →  Less than or equal to

File Test Operators

  • -e FILE → Returns true if the file exists
  • -f FILE → Returns true if the file exists and is a regular file
  • -d FILE → Returns true if the file exists and is a directory
  • -r FILE → Returns true if the file is readable
  • -w FILE → Returns true if the file is writable
  • -x FILE → Returns true if the file is executable
  • -h FILE → Returns true if the file is a symbolic link

Integer Comparison Operators

  • INTEGER1 -eq INTEGER2→ Returns true if INTEGER1 is equal to INTEGER2
  • INTEGER1 -gt INTEGER2→ Returns true if INTEGER1 is greater than INTEGER2
  • INTEGER1 -lt INTEGER2→ Returns true if INTEGER1 is less than INTEGER2
  • INTEGER1 -ge INTEGER2→ Returns true if INTEGER1 is greater than or equal to INTEGER2
  • INTEGER1 -le INTEGER2→ Returns true if INTEGER1 is less than or equal to INTEGER2

Important: Always quote strings in comparisons to prevent errors from word splitting or globbing.

Conclusion

The if statement in Bash is a powerful way to add logic to your shell scripts. The if, if…else, and if…elif…else statements in Bash allow you to control the flow of your script by evaluating specific conditions.

When a condition evaluates to false, the commands in the optional else clause will execute instead. This makes your scripts more powerful, dynamic, and adaptable to real-world tasks.

By mastering these conditionals, you can create smarter, more efficient Bash scripts that respond dynamically to user input and system states.

Anita Sreelal
Anita Sreelal