How to use if-then statement in Bash scripting

Updated: January 28, 2024 By: Guest Contributor Post a comment

Introduction

Bash scripting is a powerful tool for automating tasks in Linux and Unix-like operating systems. One of the fundamental concepts in any programming language, including Bash, is the ability to make decisions based on certain conditions using conditional statements. In Bash, the most common conditional statement is the if-then construct. This tutorial will guide you through the basics of using if-then statements in bash scripting, accompanied by multiple code examples that increase in complexity.

Understanding the Basics

At its core, an if-then statement allows a script to execute commands based on whether a condition is true or false. The basic syntax of an if-then statement in Bash is:

if [ condition ]; then
  # commands
fi

[ condition ] contains your logic. If the condition evaluates to true (exit status 0), the commands between then and fi (end of if) are executed.

Example 1: Checking if a file exists

if [ -e /path/to/file ]; then
  echo "File exists."
else
  echo "File does not exist."
fi

Example 2: Checking if a variable is equal to a specific value

MY_VAR='hello'
if [ "$MY_VAR" = 'hello' ]; then
  echo "Variable is hello."
else
  echo "Variable is not hello."
fi

Be cautious with spacing after [ and before ]. It’s essential for syntax correctness.

Logical Operators

Logical operators enable more complex conditions by combining multiple expressions. The primaries are:

  • AND operator -a or &&
  • OR operator -o or ||
  • NOT operator !

Example 3: Using AND

NUM=50
if [ "$NUM" -gt 10 ] && [ "$NUM" -lt 100 ]; then
  echo "Number is between 10 and 100."
fi

Example 4: Using OR

if [ "$NUM" -le 10 ] || [ "$NUM" -ge 100 ]; then
  echo "Number is out of range."
fi

Arithmetic Comparisons

The if-then statements become even more powerful when integrated with arithmetic comparisons. The commonly used comparison operators are:

  • Equal: -eq
  • Not equal: -ne
  • Less than: -lt
  • Greater than: -gt
  • Less than or equal: -le
  • Greater than or equal: -ge

Example 5: Using arithmetic comparisons

if [ "$NUM" -eq 50 ]; then
  echo "Number is equal to 50."
fi

Each operator serves a different comparison logic to evaluate numerical values.

Using if-then-else-fi

Adding an else clause to the if-then construct allows you to execute commands when your condition is false.

Example 6: A complete if-then-else-fi example

READ_VAL='Y'
if [ "$READ_VAL" = 'Y' ]; then
  echo "You chose yes."
else
  echo "You chose no."
fi

Using if-then-elif-else-fi

To check multiple conditions sequentially, use the elif clause. It stands for “else if.”

Example 7: Multiple conditions with elif

if [ "$NUM" -eq 50 ]; then
  echo "Number is 50."
elif [ "$NUM" -eq 100 ]; then
  echo "Number is 100."
else
  echo "Number is neither 50 nor 100."
fi

Compound Commands

Bash allows the use of compound commands with [[ for more complex conditional expressions that include pattern matching and regular expressions.

Example 8: Using pattern matching

FILE_NAME="sample.txt"
if [[ "$FILE_NAME" == *.txt ]]; then
  echo "It is a text file."
fi

Advanced If-then Usage in Scripts

More advanced scripts can include nested if-then statements, functions, and loops within if-then constructs, allowing fine-grained control over the workflow.

Example 9: Nested if-then

if [ "$NUM" -eq 50 ]; then
  if [ "$READ_VAL" == 'Y' ]; then
    echo "Number is 50 and you chose yes."
  fi
fi

Error Handling with if-then

Appropriate error handling can be implemented using if-then by checking the exit status of commands.

Example 10: Simple error handling

tar -zcf /some/path/mybackup.tar.gz /my/data/
if [ "$?" -eq 0 ]; then
  echo "Backup was successful."
else
  echo "Backup failed."
fi

The special variable $? holds the exit status of the last command executed. In the above example, it is used to determine whether the tar command was successful.

Tips for Working with if-then Statements

  • Quotes: Always use quotes around variables to prevent globbing and word splitting, especially when the value may contain spaces.
  • Double brackets: Use [[ when you need pattern matching or regex.
  • Exit status: In scripting, remember that a zero exit status corresponds to true, while a non-zero (usually 1) means false.
  • Debugging: Use set -x to enable debugging and see how your if-then conditions are evaluated as your script runs.

Conclusion

This tutorial has introduced you to the if-then statement in bash scripting, from the fundamentals to more advanced applications, supported with practical examples. Understanding the if-then construct is crucial to writing effective shell scripts that can make decisions and react accordingly. With these foundational skills, you can now create more complex and dynamic bash scripts that can consistently perform under a variety of conditions.