Moving ahead from our previous tutorial on arrays in shell scripts, let’s understand how we can use if-else in shell scripts.
Conditional programming is an important part of any programming language because executing every single statement in our program is, more often than not, undesirable.
And we need a way to conditionally execute statements. The if-else in shell scripts serves this exact situation.
One of the most important parts of conditional programming is the if-else statements. An if-else statement allows you to execute iterative conditional statements in your code.
We use if-else in shell scripts when we wish to evaluate a condition, then decide to execute one set between two or more sets of statements using the result.
This essentially allows us to choose a response to the result which our conditional expression evaluates to.
Now we know what is an if-else function and why is it important for any programmer, regardless of their domain. To understand if-else in shell scripts, we need to break down the working of the conditional function.
Let us have a look at the syntax of the if-else condition block.
Here we have four keywords, namely if, then, else and fi.
An important thing to keep in mind is that, like C programming, shell scripting is case sensitive. Hence, you need to be careful while using the keywords in your code.
It is easy to see the syntax of a function and believe you know how to use it. But it is always a better choice to understand a function through examples because they help you understand the role that different aspects of a function play.
Here are some useful examples of if-else in shell scripts to give you a better idea of how to use this tool.
Example | Description |
---|---|
if [ $a -eq $b ]; then echo "Both variables are the same"; else echo "Both variables are different"; fi |
Check if two variables are equal |
if [ $a -ge $b ]; then echo "The variable 'a' is greater than the variable 'b'."; else echo "The variable 'b' is greater than the variable 'a'."; fi |
Compare two values to find the greater one |
if [ $((a % 2)) -eq 0 ]; then echo "The number is even"; else echo "The number is odd"; fi |
Check if a number is even |
if [ -f file.txt ]; then echo "File exists"; else echo "File does not exist"; fi |
Check if a file exists |
if [ -z "$var" ]; then echo "Variable is empty"; else echo "Variable is not empty"; fi |
Check if a variable is empty |
When trying to understand the working of a function like if-else in a shell script, it is good to start things simple. Here, we initialize two variables a and b, then use the if-else function to check if the two variables are equal. The bash script should look as follows for this task.
Output:
The more common use of if-else in shell scripts is for comparing two values. Comparing a variable against another variable or a fixed value helps is used in a variety of cases by all sorts of programmers.
For the sake of this example, we will be initializing two variables and using the if-else function to find the variable which is greater than the other.
Output:
Sometimes we come across situations where we need to deal with and differentiate between even and odd numbers. This can be done with if-else in shell scripts if we take the help of the modulus operator.
The modulus operator divides a number with a divisor and returns the remainder.
As we know all even numbers are a multiple of 2, we can use the following shell script to check for us whether a number is even or odd.
Output:
As you can see, we’ve enclosed a part of the condition within double brackets. That’s because we need the modulus operation to be performed before the condition is checked.
Also, enclosing in double brackets runs statements in C-style allowing you to process some C-style commands within bash scripts.
The if-else function is known for its versatility and range of application. In this example, we will use if-else in shell script to make the interface for a password prompt.
To do this, we will ask the user to enter the password and store it in the variable pass.
If it matches the pre-defined password, which is ‘password’ in this example, the user will get the output as -“The password is correct”.
Else, the shell script will tell the user that the password was incorrect and ask them to try again.
elif
for multiple conditionsWhen you need to check multiple conditions in sequence, using nested if-else
statements can become cumbersome and difficult to read. This is where the elif
(else if) statement comes in handy. The elif
statement allows you to check multiple conditions in a more structured and readable way.
The syntax for using elif
in shell scripts is as follows:
In this example, the script checks the grade and prints the corresponding grade letter. If the grade is 90 or higher, it prints “Grade: A”. If the grade is 80 or higher, it prints “Grade: B”. If the grade is 70 or higher, it prints “Grade: C”. Otherwise, it prints “Grade: F”.
if-else
for binary decisionsBinary decisions are a fundamental aspect of programming, and if-else statements are the most common way to implement them in shell scripts. A binary decision is a choice between two options, such as true or false, yes or no, or 0 or 1. If-else statements are used to execute different blocks of code based on the outcome of a condition.
For example, consider a script that checks if a file exists and prints a message accordingly:
In this example, the script checks if the file exists using the -f
test. If the file exists, it prints “The file exists.” Otherwise, it prints “The file does not exist.”
if-else
statements for complex scenariosNested if-else statements are used to handle complex scenarios where multiple conditions need to be evaluated. They allow you to check additional conditions if the initial condition is true or false. This is particularly useful when dealing with multiple variables or conditions that need to be evaluated in a specific order.
Here’s an example of a script that checks if a number is within a certain range:
In this example, the script first checks if the number is greater than or equal to 5. If it is, it then checks if the number is less than or equal to 15. If both conditions are true, it prints “The number is within the range.” If the number is not within the range, it prints an appropriate message.
Checking file existence and permissions is a common task in shell scripting. You can use if-else statements to evaluate these conditions and take appropriate actions.
Here’s an example of a script that checks if a file exists and has read permissions:
In this example, the script first checks if the file exists using the -f
test. If the file exists, it then checks if the file has read permissions using the -r
test. If both conditions are true, it prints “The file exists and is readable.” If the file exists but does not have read permissions, it prints “The file exists but is not readable.” If the file does not exist, it prints “The file does not exist.”
User input validation is crucial in shell scripting to ensure that the input provided by the user is valid and can be processed correctly. If-else statements can be used to validate user input and prompt the user to enter valid input if necessary.
Here’s an example of a script that validates user input for a simple calculator:
In this example, the script prompts the user to enter two numbers. It then checks if both inputs are valid numbers using regular expressions. If both inputs are valid, it prints “Both numbers are valid.” and can proceed with calculations. If either input is invalid, it prints “One or both numbers are invalid. Please enter valid numbers.”
To use an if condition in a shell script, you can follow the basic syntax of an if statement. Here’s an example:
For example, to check if a file exists:
Writing an if statement in a shell script involves specifying a condition and the actions to take if the condition is true. Here’s the basic syntax:
For example, to check if a variable is greater than 10:
To write multiple if conditions in a shell script, you can use elif statements. Here’s the syntax:
For example, to check if a variable is within a certain range:
Handling complex decision-making in shell scripts can be achieved by using nested if statements, case statements, or logical operators. Here’s an example of using logical operators:
In shell scripts, the == operator is used for string comparison. It checks if the strings on both sides of the operator are equal. Here’s an example:
Note that in shell scripts, the == operator is not used for numerical comparison. For numerical comparison, use the -eq, -ne, -gt, -lt, -ge, and -le operators.
An alternative to if-else statements in shell scripting is the case statement. The case statement allows you to match a value against multiple patterns and execute different blocks of code based on the match. Here’s an example:
This example checks the value of $var and executes different blocks of code based on the value.
The function of if-else in shell script is an important asset for shell programmers. It is the best tool to use when you need to execute a set of statements based on pre-defined conditions.
The if-else block is one, if not the most essential part of conditional programming. By regulating the execution of specific statements you not only make your code more efficient but you also free up the precious time which the processor might have wasted executing statements which are unnecessary for a specific case.
We hope this tutorial was able to help you understand how to use the if-else function. If you have any queries, feedback or suggestions, feel free to reach out to us in the comments below.
If you’re interested in learning more about shell scripting, check out these tutorials:
Continue building with DigitalOcean Gen AI Platform.