Tutorial

Shell Script if else: Comprehensive Guide with Examples

Updated on April 15, 2025

Sr Technical Writer

Shell Script if else: Comprehensive Guide with Examples

Introduction

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.

Conditions in Shell Scripts

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.

How does if-else in shell scripts work ?

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.

if [condition]
then
   statement1
else
   statement2
fi

Here we have four keywords, namely if, then, else and fi.

  1. The keyword if is followed by a condition.
  2. This condition is evaluated to decide which statement will be executed by the processor.
  3. If the condition evaluates to TRUE, the processor will execute the statement(s) followed by the keyword then. In the syntax, it is mentioned as statement1.
  4. In a case where the condition evaluates to FALSE, the processor will execute the statement(s) followed by the keyword else. This is denoted as statement2 in the function syntax.

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.

How to use if-else in shell script

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

1. Using if-else to check whether two numbers are equal

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.

#!/bin/bash
m=1
n=2

if [ $n -eq $m ]
then
        echo "Both variables are the same"
else
        echo "Both variables are different"
fi

Output:

Both variables are different

2. Using if-else to compare two values

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.

#!/bin/bash
a=2
b=7
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

Output:

The variable 'b' is greater than the variable 'a'.

3. Using if-else to check whether a number is even

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.

#!/bin/bash
n=10
if [ $((n%2))==0 ]
then
  echo "The number is even."
else
  echo "The number is odd."
fi

Output:

The number is even

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.

4. Using if-else as a simple password prompt

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.

#!/bin/bash
echo "Enter password"
read pass
if [ $pass="password" ]
then
  echo "The password is correct."
else
  echo "The password is incorrect, try again."
fi

Bash Password
Bash Password

Utilizing elif for multiple conditions

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:

#!/bin/bash
grade=85
if [ $grade -ge 90 ]; then
  echo "Grade: A"
elif [ $grade -ge 80 ]; then
  echo "Grade: B"
elif [ $grade -ge 70 ]; then
  echo "Grade: C"
else
  echo "Grade: F"
fi

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”.

Implementing if-else for binary decisions

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:

#!/bin/bash
file_path="/path/to/your/file.txt"
if [ -f "$file_path" ]; then
  echo "The file exists."
else
  echo "The file does not exist."
fi

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.”

Constructing nested if-else statements for complex scenarios

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:

#!/bin/bash
num=10
if [ $num -ge 5 ]; then
  if [ $num -le 15 ]; then
    echo "The number is within the range."
  else
    echo "The number is above the range."
  fi
else
  echo "The number is below the range."
fi

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.

Creating scripts that check file existence and permissions

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:

#!/bin/bash
file_path="/path/to/your/file.txt"
if [ -f "$file_path" ]; then
  if [ -r "$file_path" ]; then
    echo "The file exists and is readable."
  else
    echo "The file exists but is not readable."
  fi
else
  echo "The file does not exist."
fi

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.”

Automating user input validation

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:

#!/bin/bash
echo "Enter the first number:"
read num1
echo "Enter the second number:"
read num2

if [[ $num1 =~ ^[0-9]+$ ]] && [[ $num2 =~ ^[0-9]+$ ]]; then
  echo "Both numbers are valid."
  # Perform calculations here
else
  echo "One or both numbers are invalid. Please enter valid numbers."
fi

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.”

FAQs

1. How to use in if condition in shell script?

To use an if condition in a shell script, you can follow the basic syntax of an if statement. Here’s an example:

if [ condition ]; then
  # code to execute if condition is true
fi

For example, to check if a file exists:

if [ -f file.txt ]; then
  echo "File exists."
fi

2. How do I write an if statement in a shell script?

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:

if [ condition ]; then
  # code to execute if condition is true
else
  # code to execute if condition is false
fi

For example, to check if a variable is greater than 10:

if [ $var -gt 10 ]; then
  echo "Variable is greater than 10."
else
  echo "Variable is not greater than 10."
fi

3. How to write multiple if conditions in shell script?

To write multiple if conditions in a shell script, you can use elif statements. Here’s the syntax:

if [ condition1 ]; then
  # code to execute if condition1 is true
elif [ condition2 ]; then
  # code to execute if condition1 is false and condition2 is true
else
  # code to execute if all conditions are false
fi

For example, to check if a variable is within a certain range:

if [ $var -ge 5 ] && [ $var -le 15 ]; then
  echo "Variable is within the range."
elif [ $var -lt 5 ]; then
  echo "Variable is less than 5."
else
  echo "Variable is greater than 15."
fi

4. How do I handle complex decision-making in shell scripts?

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:

if [ $var -ge 5 ] && [ $var -le 15 ]; then
  echo "Variable is within the range."
elif [ $var -lt 5 ] || [ $var -gt 15 ]; then
  echo "Variable is outside the range."
fi

5. What is the == operator in shell script?

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:

if [ "$var" == "value" ]; then
  echo "Variable is equal to 'value'."
fi

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.

6. What is the alternative to if-else statements in shell scripting?

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:

case $var in
  1)
    echo "Variable is 1."
    ;;
  2)
    echo "Variable is 2."
    ;;
  *)
    echo "Variable is neither 1 nor 2."
    ;;
esac

This example checks the value of $var and executes different blocks of code based on the value.

Conclusion

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.

About the author(s)

Anish Singh Walia
Anish Singh WaliaSr Technical Writer
See author profile
Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.