Quick Links
Summary
Use the Linux Bash if statement to build conditional expressions with anifthenfistructure. Addelifkeywords for additional conditional expressions, or theelsekeyword 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 ofBash 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 anifstatement. You might hear

statements called
statements, or

statements. They’re different names for the same thing.
Related:9 Examples of for Loops in Linux Bash Scripts
Theifstatement 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.
Theifstatement 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
then
execute-these-statements
fi
If the condition within the text resolves to true, the lines of script in thethenclause are executed. If you’re looking through scripts written by others, you may see theifstatement written like this:
Some points to note:
We can add an optionalelseclause to have some code executed if the condition test proves to be false. Theelseclause doesn’t need athenkeyword.
else
execute-these-statements-instead
This script shows a simple example of anifstatement that uses anelseclause. 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 thethenclause is executed. If they’re not old enough, theelseclause is executed, and they’re not allowed in.
customer_age=25
if [ $customer_age -ge 21 ]
echo “Come on in.”
echo “You can’t come in.”
Copy the script from above into an editor, save it as a file called “if-age.sh”, and usethechmodcommandto make it executable. You’ll need to do that with each of the scripts we discuss.
Let’s run our script.
Now we’ll edit the file and use an age less than 21.
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.
The elif Clause
Theelifclause adds additional conditional tests. You can have as manyelifclauses as you like. They’re evaluated in turn until one of them is found to be true. If none of theelifconditional tests prove to be true, theelseclause, 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 themoduloof 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.
echo -n “Enter a number: "
read number
if [ $number -eq 0 ]
echo “You entered zero. Zero is an even number.”
elif [ $(($number % 2)) -eq 0 ]
echo “You entered $number. It is an even number.”
echo “You entered $number. It is an odd number.”
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.
That’s all working fine.
Different Forms of Conditional Test
Thebrackets”[]" we’ve used for our conditional tests are a shorthand way of calling thetestprogram. Because of that, all the comparisons and tests thattestsupports are available to yourifstatement.
This isjust 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-eqare 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 thetestprogram on the command line.
In each case, we usetheechocommandto 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-eqoperator returns a true response.
If you want to use wildcard matching in your conditional test, use the double bracket “[[ ]]” syntax.
if [[ $USER == *ve ]]
echo “Hello $USER”
echo “$USER does not end in ’ve'”
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.
Nested If Statements
You can put anifstatement inside anotherifstatement.
This is perfectly acceptable, but nestingifstatements 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 ofifstatements, 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 nestedifstatement makes a second test. If the day is Wednesday, it tells us it is open in the morning only.
get the day as a number 1..7
day=$(date +"%u")
if [ $day -le 6 ]
the shop is open
if [ $day -eq 3 ]
Wednesday is half-day
echo “On Wednesdays we open in the morning only.”
regular week days and Saturday
echo “We’re open all day.”
not open on Sundays
echo “It’s Sunday, we’re closed.”
Copy this script into an editor, save it as a file called “if-shop.sh”, and make it executable using thechmodcommand.
We ran the script once and thenchanged the computer’s clockto be a Wednesday, and re-ran the script. We then changed the day to a Sunday and ran it once more.
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 humbleifstatement 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. Theifstatement is great, but don’t let it be the only tool in your bag. In particular, check out thecasestatement which can be a solution in some scenarios.