If you’ve ever written a Bourne Again Shell (Bash) script, you know that they can quickly become complex as you add more logic to them. How to avoid messing your scripts up? Conditional statements, like Bash if else, are one way to add logic, allowing your script to make decisions based on certain conditions.
In this tutorial, you’ll learn how to use Bash if-else and case statements to write an error-free Bash script. All these with some best practices for writing Bash scripts.
Ready? Read on and take your Bash scripting to the next level!
Table of Contents
This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have
- A Linux or Windows system with Bash installed – Windows Subsystem for Linux (WSL) is an excellent option for Windows users.
- A code/text editor.
Why Use Conditional Statements?
Conditional statements are one of the most important tools in Bash scripting as they allow you to make decisions in your scripts based on certain conditions.
For example, you could use a conditional statement to check if a file exists before trying to delete it. Or you could use one to check if a user has permission to access a certain resource.
Conditional statements make your scripts more flexible and powerful. Imagine you’re writing a script to delete all files in a directory. With a conditional statement, you can delete files that are older than 30 days.
Understanding the IF Statement
Enough with the Bash script introduction, and get your hands dirty. Take a closer look at one of the most popular conditional statements, the
if statement is the most basic way to add conditionals to your Bash scripts, with the following syntax:
- Starting with the if keyword, you specify the [[conditions]] to meet. The code inside the if statement then runs, and the statement ends with the fi keyword.
- The then keyword separates the condition from the code (statement) that will run if the condition is met. This code can be multiple lines long if you append a semicolon (;) as a line separator.
if [[ condition ]]; then statement fi
Suppose you’re creating a script that asks for the correct username for your system before logging you in:
1. Open your terminal and create a new bash_if_demo.sh file using your text editor of choice.
2. Copy and paste the following code into your bash_if_demo.sh file, save the changes, and close the file.
The code below asks for a username, and if the correct one is entered, the code prints a ‘welcome back’ message along with the current date and time.
You can log the date and time the user is trying to access the system for further analysis.
The first line #!/bin/bash (shebang) tells the system which interpreter to use to run the rest of the code in the file. In this case, you’re using bash.
#!/bin/bash # Prints a question to the screen. echo "Whats your name?" # Reads keyboard input and stores it in the $NAME variable read NAME # Starts the if statement - checks to see if the $NAME variable's value # is equal to ATA. If it is, the code inside runs. Otherwise, the code will not run. if [ $NAME == "ATA" ] then # Prints a message to the screen, only if the value stored in the $NAME variable # is equal to ATA. echo "Welcome back ATA!" fi # Prints the current date and time to the screen. Since this line is outside # of the if statement, it always runs regardless of the $NAME variable's value. date
3. Lastly, run the below command to execute the bash_if_demo.sh script to see what it does.
Note that whatever Bash shell you’re using, you must append bash before the script’s name, so that the system will use Bash to execute your code.
Input ATA then hit Enter, and you’ll see the following output.
You won’t get the welcome message if you input anything other than “ATA.”, only the current date and time. Why? Because your if statement is checking for the exact value as the one stored in the $NAME variable.
Note that if statements are case sensitive. So, “ata,” “aTa,” “Ata,” etc., are not the same as “ATA.”
Testing your code with different inputs is a best practice to make sure the code behaves as expected.
Understanding Nested If Statements
You’ve just learned the basics of writing if statements, and that’s good enough if you’re not writing a complex code. But if you do, try writing a nested if statement to expand your conditionals statements. A nested if statement is an if statement that contains one or more if statements.
Below is the basic syntax for nested if statements, where:
if [[ conditions ]]– The outer
ifstatement containing code that only runs if the condition is met. In this case, another
if [[ condition2 ]]– The inner
ifstatement containing code that only runs if both conditions are met.
if [[ conditions ]]; then if [[ condition2 ]]; then statement fi fi
Taking the previous code up a notch by setting an
if statement that asks for a password:
1. Create a new file called bash_nested_if_demo.sh with your text editor.
2. Populate the code below to the bash_nested_if_demo.sh file, save the changes, and close the file.
The code below asks for a name and a password. If both conditions are met for the name and password, the code prints a message. If not, the code won’t print any messages apart from the current date and time.
#!/bin/bash # Prints a message asking for a name. echo "Whats your name?" # Reads input from the keyboard. read NAME # Check if the $NAME variable's value is equal to "ATA." if [ $NAME == "ATA" ] then # Prints a message asking for a password. echo "Password" # Reads input from the keyboard. read Password # Nested if statement - Check if the $Password variable's value equals "pwd123." if [ "$Password" == "pwd123" ]; then # Prints a message if both conditions for name and password are met. echo "You logged in as ATA" fi fi # Prints the current date and time date
3. Lastly, run the below command to execute the bash_nested_if_demo.sh script.
Enter ATA for the name and pwd123 for the password.
If you enter anything other than “ATA” or “pwd123”, the only message you’ll get is the current date and time. Why? Both conditions in your nested if statements must be met.
Understanding IF ELSE Statements
The if statement is a powerful and commonly used tool in Bash scripting. if statements can help make decisions in your scripts. But it’s worth noting that there are some drawbacks to using if statements.
The main drawback is that if statements can make your code hard to read and maintain, especially if you have nested if statements inside other if statements. This scripting style can lead to what is known as “spaghetti code” — difficult to read and understand.
So how do you make your code not look complicated? Use if else statements instead of a bunch of nested if statements. The else keyword allows you to specify code that will run if the condition in the if statement is not met.
Look into the IF ELSE statement’s syntax below, where:
if [[ conditions ]]– The
ifstatement, which contains the code (
statement1) that will run if the condition is met.
elsestatement contains the code (
statement2) that will run if the condition in the
ifstatement is not met.
if [[ conditions ]]; then statement1 else statement2 fi
Suppose you’re creating a number game, which takes a random number as input from the user:
1. Create a new file called bash_if_else_demo.sh.
2. Add the following code to your bash_if_else_demo.sh file, save the changes, and close the file.
The code below prints a message asking for the user’s lucky number and prints the You Won message if the user’s input is an even number. Otherwise (else), the code prints the You Lost message if the user’s input is an odd number.
#!/bin/bash # Prints a message asking for the user's lucky number echo -n "Enter You Lucky Number:" # Reads the keyboard input. read var # Checks if the value is an even number. if [ $((var%2)) == 0 ]; then # Prints a message if the condition is met echo "You Won!" else # Prints a message if the condition is not met echo "You Lost!" fi
3. Now, run the following command to execute the bash_if_else_demo.sh script.
If you enter an even number, the message “You Won!” prints, as you can see below. But if you enter an odd number, the message “You Lost!” prints instead.
Try improving your code by adding another statement that checks if the user enters a letter of a special character instead.
Understanding Case Statements
So far, you’ve looked at two ways to make decisions in your Bash scripts:
if statements and
else statements. But there’s another way to make decisions in your scripts, the
case statement is similar to the
if statement as it allows you to specify code that will run based on a condition. But the good thing about the case statement is that you’ll have a more precise and concise syntax than the nested
The syntax for the case statement is as follows where:
case $VAR in– The
casestatement that takes the
$VARvariable tests against the patterns you specify until a match is found.
pattern2)-The patterns to test, which runs the code (
statement2) once a pattern is found.
esac– Ends the case statement.
case $VAR in pattern1) statement1 ;; pattern2) statement2 ;; esac
Suppose you need a script that asks users to input their country names and respond with a message displaying the language spoken in that country.
1. Create a new file called bash_case_demo.sh.
2. Populate the code below to the bash_case_demo.sh file, save the changes and close the file.
The code below asks the user for a country name and prints the official language of that country based on the patterns in a case statement.
3#!/bin/bash # Prints a message asking for the user's country name echo -n "Enter the Country You Live In:" # Reads keyboard input. read var # Prints a message showing the official language in the user's country ($var) # based on the pattern in the case statement. echo -n "The official language of $var is " # Case statement - checks if the user's input ($var) matches the patterns. case $var in # Define patterns that print the user's country's official language. US) echo -n "English" ;; Canada) echo -n "English | French" ;; Algeria | Bahrain | Egypt| Jordan) echo -n "Arabic" ;; *) echo -n "unknown" ;; esac
3. Finally, run the following command to execute the bash_case_demo.sh script.
Below, you can see that the appropriate official language prints depending on what country the user entered.
If the country entered doesn’t match any of the patterns, the default pattern (*) is used, and the unknown message prints.
In this tutorial, you’ve taken your first steps in learning how to use conditional statements in Bash. You’ve learned to ease up complex code with Bash if statement, if-else statement, and case statement.
You’re now confident enough to use conditional statements to write Bash scripts more efficiently and with fewer errors.
But don’t stop here! There are more things conditional statements in Bash can offer. Perhaps start learning about the Bash elif statement and &&, OR and || operators? With a bit of practice, you’ll be writing Bash scripts like a pro in no time!