Conditional statements are an important part of every coding language. They allow you to write code that runs only when certain conditions are met. This means that you can have a program which returns different responses depending on whether certain factors are true.
In bash, you can use if statements to make decisions in your code. if statements also come with additional keywords, else
and elif
, which give you even more control over how your program executes.
In this guide, we’re going to walk through the if...else
statement in bash. We’ll also create an example program so you can quickly get started using if...else
.
How to Write an if Statement
Let’s start by focusing on the basics: the if statement. An if statement will evaluate whether a statement is true or false. If the statement is true, the code in the if statement will run.
The format of an if statement is like this:
if [a condition is met] then [ do this ] fi
This code sounds a lot like English. If the condition you specify is met, then the code that comes after the “then” keyword will be executed. Otherwise, nothing will happen.
Notice that in this code the contents of our “then” block of code are indented. This is important to note because using indents makes your code more readable, thereby reducing the chance that you make an error. Technically, you don’t have to indent your code. However, indenting your code will make your applications more maintainable.
Let’s create a program that calculates whether a student has passed a seventh grade math test. Create a file called script.sh and paste in the following code:
echo -n "Enter a grade: " read GRADE if [[ $GRADE -gt 50 ]] then echo "The student has passed their test!" fi
In this code, we ask the user to enter the numerical grade a student has earned on their test. We then read this grade into our program and use an if statement to check whether that grade is greater than 50. If it is, the message “The student has passed their test!” is printed to the console. Let’s try out our program by running bash script.sh
:
Enter a grade: 70 The student has passed their test!
In this example, we’ve entered a grade greater than 50. This prompts our “echo” statement to be executed in the “then” clause of our if statement. Here’s what happens when you enter a value less than 50:
Enter a grade: 50
As you can see, no message is printed. That’s because the condition in our if statement was not met, so the code in our “then” statement was not executed.
How to Write an Else Statement
When you’re checking for a condition, it’s likely that you want something to happen even if your condition is not met. In our example above, we would want a message to appear informing a teacher that a student has failed their test if their grade is below 50.
We could do this by adding an else
statement to our code:
echo -n "Enter a grade: " read GRADE if [[ $GRADE -gt 50 ]] then echo "The student has passed their test!" else echo "The student has failed their test!" fi
Let’s run our program again and try to insert the value 42:
Enter a grade: 42 The student has failed their test!
Our script now prints out a message when the user has failed their test. Else
statements are run if none of the conditions you have specified in an if statement match.
In this case, the student’s grade was less than 50, which meant our if statement condition was not met. As a result, the code in our else
statement was executed.
If we insert a value greater than 50, the code inside our “then” clause is executed:
Enter a grade: 57 The student has passed their test!
Using an else
statement, we can write a two-part conditional. If our condition is met, a block of code will be run; otherwise, another block of code will be run.
Boolean Operations with Bash Scripts
When you’re writing a bash script, you may only want something to happen if multiple conditions are met, or if one of multiple conditions are met. You can use these operators to check for these cases:
- Multiple conditions: &&
- One of multiple conditions: ||
For instance, you may only want a student to be given a passing grade if their grade is higher than 50 and if their test has been peer-reviewed by another teacher.
We could make this happen using the following code:
echo -n "Enter a grade: " read GRADE echo -n "Has this test been peer reviewed? " read PEER_REVIEW if [[ $GRADE -gt 50 && PEER_REVIEW == "Y" ]] then echo "The student has passed their test!" else echo "The student has failed their test!" fi
Let’s enter a student’s grade and tell our program that the student’s test has been peer reviewed:
Enter a grade: 62 Has this test been peer reviewed? Y The student has passed their test!
Now, let’s see what happens when we tell our program that a student’s test has not been peer reviewed who has earned the same grade (62):
Enter a grade: 62 Has this test been peer reviewed? N The student has failed their test!
Because both of our conditions were not met – GRADE being over 50 and PEER_REVIEW being equal to “Y” – then the contents of our else
statement were executed.
We could substitute the && for a || symbol if we wanted to check whether one of multiple conditions evaluated to true.
How to Write an Elif Statement
While you may only need to check for two conditions, there are plenty of cases where you may want to evaluate multiple different statements. That’s where the elif
statement comes in handy.
Let’s make our grade calculator a little more advanced. Suppose we want to calculate a student’s letter grade based on their numerical grade. We want to assign the following letters based on a student’s grade:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
- 86 or above is considered an A
- 71 to 85 is considered a B
- 61 to 70 is considered a C
- 51 to 60 is considered a D
- Below 50 is considered an F
For this code, we are going to need to use an if, elif
and else
statements.
Open up the script.sh file from earlier and change the if statement to use the following code:
echo -n "Enter a grade: " read GRADE if [[ $GRADE -ge 86 ]]; then echo "The student has earned an A grade." elif [[ $GRADE -ge 71 ]]; then echo "The student has earned a B grade." elif [[ $GRADE -ge 61 ]]; then echo "The student has earned a C grade." elif [[ $GRADE -ge 51 ]]; then echo "The student has earned a D grade." else echo "The student has earned an F grade." fi
There’s a lot going on in our code, so let’s break it down.
First, we use an if statement to check if a student’s grade is greater than 86. If it is, the student has earned an A grade. If this statement evaluates to false, our program will check whether the student’s grade is greater than 71 using the -ge operator.
If this does not evaluate to true, our program will keep going through our grade boundary checker.
If a student’s grade does not meet any of our if or elif
conditions, the contents of the else
block of code are executed. This returns an F grade for the student.
Nested if Statements
There’s no limit to how many if statements you can have inside your bash script. What’s more, if statements can be contained within themselves. This means that you can check for a condition only when another condition is met.
Suppose we want to check whether a student’s grade is even or odd, but only if they passed their test. We could do so using this code:
echo -n "Enter a grade: " read GRADE if [[ $GRADE -gt 50 ]] then echo "The student has passed their test!" if (( $GRADE % 2 == 0 )) then echo "This grade is an even number." else echo "This grade is an odd number." fi fi
In this code, our program first checks to see whether a student’s grade is greater than 50. If it is, a message is printed to the console. Next, our program checks whether a student’s grade is an even number. We do this using the following line of code:
(( $GRADE % 2 == 0 ))
This code uses the modulo operator (%) to check whether our number is even or odd. If it is even, a message stating the number is even is printed to the console; otherwise, a message stating that the number is odd is printed to the console.
Let’s run our code:
Enter a grade: 95 The student has passed their test! This grade is an odd number.
When a student’s grade is greater than 50, our program calculates whether their grade is an odd or an even number. Let’s see what happens if we insert a grade lower than 50:
Enter a grade: 49
Our code doesn’t return anything because the condition in our if statement is not met.
Conclusion
The if, if…else, and elif keywords allow you to control the flow of your code. Using an if statement, you can check whether a specific condition is met. Elif statements allow you to check for multiple conditions. Else statements execute only if no other condition is met.
Here are a few challenges for you if you are interested in building your knowledge of if statements:
- Create an application that calculates the price of a ticket to a theme park based on the age of its customers
- Create an application that checks whether a file is executable
- Create an application that figures out which of two files was updated most recently
For reference, you can check out the devhints.io Bash scripting guide. This provides a list of possible options for use with a conditional statement.
Now you’re ready to start using bash if…else statements like a scripting expert!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.