Oct 17, 2023 6 min read

Bash if..else Statement

Understand bash if-else statements with our step-by-step tutorial. It allows you to perform execution of commands based on certain conditions.

Bash if..else Statement
Table of Contents

Introduction

Before we start discussing bash if-else statement, let's understand-What is an if-else Statement ?

The if..else statement in Bash allows you to perform conditional execution of commands based on certain conditions. It enables your script to make decisions and execute different code blocks depending on whether a condition is true or false. The if..else statement is a fundamental construct in scripting and provides great flexibility in controlling the flow of your Bash scripts.

In this tutorial, we will go through the fundamentals of the Bash if Statement and demonstrate how to utilize it in your shell scripts. We will also address a few FAQs on bash if-else statement.

if Statement

if conditionals can take different forms, it's a joke. The most fundamental if statement is as follows:

if TEST-COMMAND
then
  STATEMENTS
fi

The if statement is made up of three keywords: if, conditional phrase, and then. The fi keyword brings the statement to a close.

The STATEMENTS are executed if the TEST-COMMAND evaluates to True. Nothing happens if TEST-COMMAND returns False; the STATEMENTS are ignored.

In general, it's a good idea to indent your code and use blank lines to separate code blocks. The most common indentation methods are 4-space and 2-space indentation. Your code will be more understandable and organized if you use indentations and blank lines.

Take a look at the example script below, which checks whether a given integer is greater than ten:

#!/bin/bash

echo -n "Enter a number: "
read VAR

if [[ $VAR -gt 10 ]]
then
  echo "The variable is greater than 10."
fi

Save the following code to a file and run it from the command prompt:

bash test.sh

You will be asked to enter a number by the script. If you type 15, for example, the test command will evaluate to true because 15 is greater than 10, and the echo command will be run inside the then clause.

Output

The variable is greater than 10.

if..else Statement

The if..else sentence in Bash looks like this:

if TEST-COMMAND
then
  STATEMENTS1
else
  STATEMENTS2
fi

The STATEMENTS1 will be executed if the TEST-COMMAND evaluates to True. Otherwise, the STATEMENTS2 will be executed if TEST-COMMAND returns False. In a statement, there can only be one else clause.

To the preceding sample script, let's add an else clause:

#!/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 or less than 10."
fi

If you execute the code and enter a number, the script will print a different message depending on whether the number is larger than 10 or less than 10.

if..elif..else Statement

The if..elif..else sentence in Bash looks like this:

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

The STATEMENTS1 will be executed if the TEST-COMMAND1 evaluates to True. The STATEMENTS2 will be executed if the TEST-COMMAND2 evaluates to True. STATEMENTS2 is run if none of the test instructions evaluate to True.

The statement can have one or more elif clauses. The else clause is not required.

The conditions are weighed one by one. The remaining conditions are not executed once a condition returns True, and program control shifts to the end of the if statements.

To the above script, add an elif clause:

#!/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

In Bash, if statements can be nested within other if statements. It's possible to nest multiple if statements inside another if statement.

The script below will ask you to enter three numbers and then output the largest of the 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

You will get an output like below:

Enter the first number: 4
Enter the second number: 7
Enter the third number: 2
7 is the largest number.
ℹ️
Using the case statement rather than nested if statements is generally more efficient.

Multiple Conditions

If you utilize the logical OR and AND operators in your if statements, you can employ several conditions.

Here's a different version of the script that prints the largest number out of the three. Instead of nested if statements, we use the logical AND (&&) operator in this version.

#!/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

Test Operators

The test command in Bash can take one of the following syntactic forms:

test EXPRESSION
[ EXPRESSION ]
[[ EXPRESSION ]]

Use the old test [ command, which is accessible on all POSIX shells, to make the script portable. On most recent systems with Bash, Zsh, or Ksh as the default shell, the new enhanced version of the test command [[ (double brackets) is supported.

Use the logical NOT (!) operator to negate the test statement. To avoid word splitting and globbing difficulties, always use single or double quotes when comparing strings.

Some of the most regularly utilized operators are listed below:

  • -n VAR - True if VAR has a length greater than zero.
  • -z VAR - If the VAR is empty, this value is true.
  • STRING1 = STRING2 - If STRING1 and STRING2 are equal, then True.
  • STRING1 != STRING2 - If STRING1 and STRING2 are not equal, then True.
  • INTEGER1 -eq INTEGER2 - If INTEGER1 and INTEGER2 are equal, then True.
  • INTEGER1 -gt INTEGER2 - If INTEGER1 is greater than INTEGER2, then True.
  • INTEGER1 -lt INTEGER2 - If INTEGER1 is less than INTEGER2, then True.
  • INTEGER1 -ge INTEGER2 - If INTEGER1 is equal or greater than INTEGER2, then True.
  • INTEGER1 -le INTEGER2 - If INTEGER1 is equal or less than INTEGER2, then True.
  • -h FILE - If the FILE exists and is a symbolic link, then True.
  • -r FILE - If the FILE exists and is readable, then True.
  • -w FILE - If the FILE exists and is writable, then True.
  • -x FILE - If the FILE exists and is executable, then True.
  • -d FILE - If the FILE exists and is a directory, then True.
  • -e FILE - If the FILE exists and is a file, regardless of type (node, directory, socket, etc.).
  • -f FILE - True if the FILE exists and is a regular file (not a directory or device), then True.

FAQs on Bash if..else Statement

What is the purpose of the condition in the if..else statement?

The condition is an expression or set of expressions that are evaluated by the bash interpreter. If the condition evaluates to true, the commands within the then block are executed. Otherwise, the commands within the else block are executed.

How do I specify multiple conditions in the if..else statement?

You can specify multiple conditions using logical operators such as && for AND, || for OR, or by nesting if statements within each other.

Can I use comparison operators in the condition of the if..else statement?

Yes, you can use comparison operators, such as ==, !=, <, >, <=, and >=, to compare values within the condition. These operators enable you to check if values are equal, not equal, or have certain relations.

Can I use string comparisons in the if..else statement?

Yes, you can use string comparisons in the if..else statement using operators like ==, !=, <, >, <=, and >=. These operators allow you to compare strings based on their lexicographic order.

Can I use logical operators like AND (&&) or OR (||) in the condition?

Yes, you can use logical operators like AND (&&) and OR (||) in the condition to combine multiple conditions together. These operators allow you to create complex conditions for your if..else statement.

Can I use the elif statement instead of nesting if statements?

Yes, you can use the elif statement instead of nesting multiple if statements for better readability. The elif statement checks an additional condition if the previous condition(s) in the if block evaluate to false.

Can I use the test command within the if..else statement?

Yes, you can use the test command (or its shorthand [ ]) within the if..else statement. The test command is often used to evaluate conditions, such as file existence or numeric comparisons.

Conclusion

By analyzing supplied criteria, the if, if..else, and if..elif..else statements allow you to control the flow of the Bash script's execution.

If you have any queries, please leave a comment below and we’ll be happy to respond to them.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Blog - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.