Tools: Shell Script if else: Comprehensive Guide with Examples
Source: DigitalOcean
By Anish Singh Walia and Manikandan Kurup 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. We also need a way to conditionally execute statements. The if-else in shell scripts serves this exact situation. Note: All examples in this article are written for Bash (/bin/bash). While many concepts also apply to other POSIX-compliant shells, some features used here, such as [[ ... ]], arithmetic evaluation with (( ... )), and regular expression matching are Bash-specific and may not work in shells like sh or dash. One of the most important parts of conditional programming is the if-else statement. An if-else statement allows you to conditionally execute statements based on the result of an expression. This allows us to choose a response based on the result of the conditional expression. Now we know what an if-else statement is and why it is 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 with respect to variables and commands, so you must use variables and commands with the correct casing. 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. 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 statement to check if the two variables are equal. The Bash script should look as follows for this task. 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 is common in many scenarios. For the sake of this example, we will be initializing two variables and using the if-else statement to find the variable which is greater than the other. 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. In this example, we use Bash arithmetic evaluation with double parentheses (( )). This allows us to perform arithmetic operations directly, without relying on test brackets or command substitution. Inside (( )), Bash evaluates the expression using C-style arithmetic, so operators like %, ==, <, and > work as expected. This approach is cleaner, more readable, and less error-prone than using [ ] with arithmetic expansion. The if-else statement 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. When 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”. Binary 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.” Nested 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 inside [[ ]]. It checks if the strings on both sides of the operator are equal. Here’s an example: Note that inside double brackets [[ ]], == is used for string comparison. However, inside double parentheses (( )), == is the standard operator for numeric equality. For basic single-bracket [ ] tests, use -eq for numbers and = for strings for maximum portability. 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 time that would otherwise be spent executing unnecessary statements. We hope this tutorial was able to help you understand how to use the if-else statement. 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: Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about our products I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers. Please complete your information! Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation. Full documentation for every DigitalOcean product. The Wave has everything you need to know about building a business, from raising funding to marketing your product. Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter. New accounts only. By submitting your email you agree to our Privacy Policy Scale up as you grow — whether you're running one virtual machine or ten thousand. Sign up and get $200 in credit for your first 60 days with DigitalOcean.* *This promotional offer applies to new accounts only.