How to Use If-Else in Shell Scripts

Anastasios Antoniadis

Shell scripting is an essential skill for system administrators, developers, and DevOps engineers. One of the fundamental constructs in shell scripting is the if-else statement, which enables conditional execution of commands. This guide provides an in-depth look at how to use if-else in shell scripts, covering syntax, examples, best practices, and troubleshooting tips.

Understanding If-Else in Shell Scripts

In shell scripting, the if-else construct allows the execution of different code blocks based on the evaluation of a condition. The general syntax is:

if [ condition ]; then
    # Code to execute if the condition is true
elif [ another_condition ]; then
    # Code to execute if the first condition is false and another_condition is true
else
    # Code to execute if all conditions are false
fi

The if statement evaluates an expression inside square brackets ([]) or double brackets ([[]] for extended test conditions). The then keyword marks the beginning of the code block that executes if the condition is met. The elif (else if) clause allows checking multiple conditions, and else defines the default action when all conditions fail. Finally, fi closes the if-else block.

Basic If-Else Example

Consider a simple script that checks if a given number is positive:

#!/bin/bash
read -p "Enter a number: " num
if [ "$num" -gt 0 ]; then
    echo "The number is positive."
else
    echo "The number is not positive."
fi

Explanation:

  1. The script prompts the user for a number.
  2. It checks if the number is greater than zero (-gt is the comparison operator for greater than).
  3. If the condition is true, it prints “The number is positive.”
  4. Otherwise, it prints “The number is not positive.”

Using If-Else with File Checks

Shell scripts often interact with files. Below is an example that checks if a file exists:

#!/bin/bash
read -p "Enter filename: " filename
if [ -e "$filename" ]; then
    echo "File exists."
else
    echo "File does not exist."
fi

Explanation:

  • -e checks if the file exists.
  • The user inputs a filename, and the script verifies its existence.

Other common file test options:

  • -f: Checks if a file exists and is a regular file.
  • -d: Checks if a directory exists.
  • -s: Checks if a file is not empty.
  • -r: Checks if a file is readable.
  • -w: Checks if a file is writable.
  • -x: Checks if a file is executable.

Using If-Else with Strings

To compare strings in a shell script, use = or !=:

#!/bin/bash
read -p "Enter your name: " name
if [ "$name" = "Alice" ]; then
    echo "Hello, Alice!"
else
    echo "You are not Alice."
fi

Explanation:

  • = checks if the entered string matches “Alice”.
  • != could be used to check if the strings are not equal.
  • Always use double quotes around variables to prevent errors with empty values.

Using Logical Operators in If-Else

Logical operators can be used to combine conditions:

#!/bin/bash
read -p "Enter a number: " num
if [ "$num" -gt 0 ] && [ "$num" -lt 100 ]; then
    echo "The number is between 1 and 99."
else
    echo "The number is out of range."
fi

Logical Operators:

  • && (AND): Both conditions must be true.
  • || (OR): At least one condition must be true.
  • ! (NOT): Negates a condition.

Examples & Use Cases

1. Using if-else to Check if Two Numbers are Equal

When learning how the if-else statement works in a shell script, it’s best to start with simple examples. In this case, we initialize two variables, m and n, and use if-else to check if they are equal.

Bash Script:

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

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

Output:

Variables are different

2. Using if-else to Compare Two Values

A common use of if-else in shell scripting is comparing two values. This is useful for evaluating conditions where one variable is compared to another or to a fixed value.

In this example, we initialize two variables, a and b, and use if-else to determine which one is greater.

Bash Script:

#!/bin/bash
a=3
b=8

if [ "$a" -ge "$b" ]; then
    echo "The variable 'a' is greater than or equal to the variable 'b'."
else
    echo "The variable 'b' is greater than the variable 'a'."
fi

Output:

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

3. Using if-else to Check if a Number is Even or Odd

Sometimes, we need to determine whether a number is even or odd. This can be done using the modulus operator (%), which returns the remainder when a number is divided by another.

Since even numbers are divisible by 2 without a remainder, we can use the following script to check if a number is even or odd.

Bash Script:

#!/bin/bash
n=16

if [ $((n % 2)) -eq 0 ]; then
    echo "The number is even."
else
    echo "The number is odd."
fi

Output:

The number is even.

Note: The modulus operation needs to be evaluated before checking the condition. We enclose the expression inside $(( )) to perform arithmetic calculations in Bash.

4. Using if-else for a Simple Password Prompt

The if-else statement is highly versatile and can be used in various applications, such as creating a simple password prompt.

In this example, the script prompts the user to enter a password. If the entered password matches the predefined value ("password"), it confirms success; otherwise, it prompts the user to try again.

Bash Script:

#!/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

Output (Example):

Enter password:
password
The password is correct.

or

Enter password:
wrongpass
The password is incorrect, try again.

Note:

  • We use = for string comparison inside [ ], not == (which is used inside [[ ]]).
  • We enclose $pass in double quotes ("$pass") to prevent issues if the user enters a value with spaces.

Best Practices for If-Else in Shell Scripts

  1. Use [[ ... ]] for safer condition checking: This prevents errors in string comparisons.
  2. Quote variables: Avoids issues when a variable is empty or contains spaces.
  3. Indent code properly: Improves readability.
  4. Use elif for multiple conditions: Avoids nesting too many if statements.
  5. Test scripts with different inputs: Ensures robustness.

Glossary

  • Condition: An expression evaluated to true or false.
  • if Statement: A control structure that executes code based on a condition.
  • elif Clause: Allows additional conditions if the initial condition is false.
  • else Clause: Defines the fallback action when all conditions fail.
  • fi Keyword: Terminates an if-else block.
  • Test Command ([]): Evaluates conditions within an if statement.
  • Logical Operators: &&, ||, and ! used for complex conditions.
  • File Test Operators: -e, -f, -d, etc., used to check file properties.
  • String Comparison Operators: =, !=, -z (empty check), -n (non-empty check).

FAQ

Q1: What is the difference between [ ... ] and [[ ... ]]?

[[ ... ]] is more powerful and allows pattern matching and safer string comparisons. [ ... ] is the traditional POSIX-compliant test command.

Q2: How do I compare numbers in shell scripts?

Use -eq, -ne, -lt, -gt, -le, and -ge. Example:

if [ "$num" -gt 10 ]; then
    echo "Greater than 10"
fi

Q3: How do I check if a variable is empty?

Use -z:

if [ -z "$var" ]; then
    echo "Variable is empty"
fi

Q4: Can I use if without else?

Yes, else is optional. If the condition is false, no action will be taken.

Q5: How do I use if-else in a single line?

Use && and ||:

[ "$num" -gt 0 ] && echo "Positive" || echo "Non-positive"

This guide should help you master the use of if-else in shell scripts. Happy scripting!

Anastasios Antoniadis
Find me on
Latest posts by Anastasios Antoniadis (see all)

Leave a Comment