If-Then-Else Statement in bash

Bash scripting offers a straightforward way to add decision-making logic to your commands: the if-then-else statement. Let’s explore how this simple structure can empower your scripts.

What is an If-Then-Else Statement?

Think of it as a fork in the road for your script:

  • If a condition is met, take one path.
  • Then execute the commands on that path.
  • Else (if the condition isn’t met), take a different path.

Syntax Breakdown

if [ condition ]; then
  statements # Execute if condition is true
else
  statements # Execute if condition is false (optional)
fi

Important Notes:

  • Spaces Matter: Notice the spaces around the square brackets [] – they’re essential!
  • Conditions: Use comparison operators (-eq, -ne, -lt, -gt, etc.) to compare values, or commands like grep to check for patterns in files.

Examples

Example 1: Checking File Contents

filename="myfile.txt"
search_term="important"

if grep -q "$search_term" "$filename"; then
  echo "$filename has important stuff!"
else
  echo "$filename does not have important stuff."
fi

Example 2: Comparing Numbers

value1=10
value2=5

if [ "$value1" -gt "$value2" ]; then
  echo "$value1 is greater than $value2"
else
  echo "$value1 is not greater than $value2"
fi

Output:

10 is greater than 5

Example 3: Testing File Existence

filename="important_data.txt"

if [ -f "$filename" ]; then
  echo "$filename exists!"
else
  echo "$filename does not exist."
fi

Why Use If-Then-Else?

  • Clear Logic: It’s easy to understand the flow of your script’s decisions.
  • Flexible: You can nest multiple if-then-else statements for more complex scenarios.