How to Use Bash If Statements (With 4 Examples)

Publish date: 2024-10-31

Quick Links

Key Takeaways

Use the Linux Bash if statement to build conditional expressions with an if then fi  structure. Add elif keywords for additional conditional expressions, or the else keyword to define a catch-all section of code that's executed if no previous conditional clause was executed.

All non-trivial Bash scripts need to make decisions. The Bash if statement lets your Linux script ask questions and, depending on the answer, run different sections of code. Here's how they work.

What Is Conditional Execution?

In all but the most trivial of Bash scripts, there's usually a need for the flow of execution to take a different path through the script, according to the outcome of a decision. This is called conditional execution.

One way to decide which branch of execution to take is to use an if statement. You might hear

if  

statements called

if then 

statements, or

if then else 

statements. They're different names for the same thing.

Related: 9 Examples of for Loops in Linux Bash Scripts

The if statement says that if something is true, then do this. But if the something is false, do that instead. The "something" can be many things, such as the value of a variable, the presence of a file, or whether two strings match.

Conditional execution is vital for any meaningful script. Without it, you're very limited in what you can get your script to do. Unless it can make meaningful decisions you won't be able to take real-world problems and produce workable solutions.

The if statement is probably the most frequently used means of obtaining conditional execution. Here's how to use it in Bash scripting.

Related: How to Check If a File Exists in Linux Bash Scripts

A Simple If Statement Example

This is the canonical form of the simplest if statement:

if [ this-condition-is-true ]  

then

execute-these-statements

fi

If the condition within the text resolves to true, the lines of script in the then clause are executed. If you're looking through scripts written by others, you may see the if statement written like this:

if [ this-condition-is-true ]; then  

execute-these-statements

fi

Some points to note:

We can add an optional else clause to have some code executed if the condition test proves to be false. The else clause doesn't need a then keyword.

if [ this-condition-is-true ]  

then

execute-these-statements

else

execute-these-statements-instead

fi

This script shows a simple example of an if statement that uses an else clause. The conditional test checks whether the customer's age is greater or equal to 21. If it is, the customer can enter the premises, and the then clause is executed. If they're not old enough, the else clause is executed, and they're not allowed in.

#!/bin/bash  

customer_age=25

if [ $customer_age -ge 21 ]

then

echo "Come on in."

else

echo "You can't come in."

fi

Copy the script from above into an editor, save it as a file called "if-age.sh", and use the chmod command to make it executable. You'll need to do that with each of the scripts we discuss.

chmod +x if-age.sh

Let's run our script.

./if-age.sh

Now we'll edit the file and use an age less than 21.

customer_age=18

Make that change to your script, and save your changes. If we run it now the condition returns false, and the else clause is executed.

./if-age.sh

The elif Clause

The elif clause adds additional conditional tests. You can have as many elif clauses as you like. They're evaluated in turn until one of them is found to be true. If none of the elif conditional tests prove to be true, the else clause, if present, is executed.

This script asks for a number then tells you if it is odd or even. Zero is an even number, so we don't need to test anything.

All other numbers are tested by finding the modulo of a division by two. In our case, the modulo is the fractional part of the result of a division by two. If there is no fractional part, the number is divisible by two, exactly. Therefore it is an even number.

#!/bin/bash  

echo -n "Enter a number: "

read number

if [ $number -eq 0 ]

then

echo "You entered zero. Zero is an even number."

elif [ $(($number % 2)) -eq 0 ]

then

echo "You entered $number. It is an even number."

else

echo "You entered $number. It is an odd number."

fi

To run this script, copy it to an editor and save it as "if-even.sh", then use chmod to make it executable.

Let's run the script a few times and check its output.

./if-even.sh

That's all working fine.

Different Forms of Conditional Test

The brackets[] " we've used for our conditional tests are a shorthand way of calling the test program. Because of that, all the comparisons and tests that test supports are available to your if statement.

This is just a few of them:

In the table, "file" and "directory" can include directory paths, either relative or absolute.

The equals sign "=" and the equality test -eq are not the same. The equals sign performs a character by character text comparison. The equality test performs a numerical comparison.

We can see this by using the test program on the command line.

test "this string" = "this string"
test "this string" = "that string"
test 1 = 001
test 1 -eq 001

In each case, we use the echo command to print the return code of the last command. Zero means true, one means false.

Using the equals sign " = " gives us a false response comparing 1 to 001. That's correct, because they're two different strings of characters. Numerically they're the same value---one---so the -eq operator returns a true response.

If you want to use wildcard matching in your conditional test, use the double bracket " [[ ]] " syntax.

#!/bin/bash  

if [[ $USER == *ve ]]

then

  echo "Hello $USER"

else

  echo "$USER does not end in 've'"

fi

This script checks the current user's account name. If it ends in "ve", it prints the user name. If it doesn't end in " ve ", the script tells you so, and ends.

./if-wild.sh

Nested If Statements

You can put an if statement inside another if statement.

This is perfectly acceptable, but nesting if statements makes for code that is less easy to read, and more difficult to maintain. If you find yourself nesting more than two or three levels of if statements, you probably need to reorganize the logic of your script.

Here's a script that gets the day as a number, from one to seven. One is Monday, seven is Sunday.

It tells us a shop's opening hours. If it is a weekday or Saturday, it reports the shop is open. If it is a Sunday, it reports that the shop is closed.

If the shop is open, the nested if statement makes a second test. If the day is Wednesday, it tells us it is open in the morning only.

#!/bin/bash  

# get the day as a number 1..7

day=$(date +"%u")

if [ $day -le 6 ]

then

## the shop is open

if [ $day -eq 3 ]

then

# Wednesday is half-day

echo "On Wednesdays we open in the morning only."

else

# regular week days and Saturday

echo "We're open all day."

fi

else

# not open on Sundays

echo "It's Sunday, we're closed."

fi

Copy this script into an editor, save it as a file called "if-shop.sh", and make it executable using the chmod command.

We ran the script once and then changed the computer's clock to be a Wednesday, and re-ran the script. We then changed the day to a Sunday and ran it once more.

./if-shop.sh
./if-shop.sh
./if-shop.sh

Related: How to Use Double Bracket Conditional Tests in Linux

The case For if

Conditional execution is what brings power to programming and scripting, and the humble if statement might well be the most commonly used way of switching the path of execution within code. But that doesn't mean it's always the answer.

Writing good code means knowing what options you have and which are the best ones to use in order to solve a particular requirement. The if statement is great, but don't let it be the only tool in your bag. In particular, check out the case statement which can be a solution in some scenarios.

Related: How to Use Case Statements in Bash Scripts

ncG1vNJzZmivp6x7qbvWraagnZWge6S7zGhvcWxgaIZwtM6wZK2nXarApnnBmqqhZZmberTAwK2cpp2eqcBuw8itn2adqJa6sbjErGY%3D