Skip to main content

Learn Bash Scripting

Chapter #7: How to Use If Statements in Bash

In this article, we’ll help you level up your Bash scripting by adding decision-making power to your code with if statements.

So far, we’ve been building a strong foundation in Bash scripting - creating scripts, using variables, handling user input, and playing with globbing and redirection. But up until now, our scripts have been kinda... one-track minded. They do something, and that’s it - no questions asked.

But what if we want our script to make decisions?

Welcome to the world of control flow!

In this chapter, we're stepping up our game by teaching your Bash scripts how to think. Well, not literally, but close enough! We'll introduce the mighty if statement - your go-to tool when you want your script to behave differently based on conditions.

Whether you're checking a number, comparing strings, or evaluating the result of a command, if statements let your script react and adapt. This is where automation really starts to feel smart.

Don’t worry if you’ve never seen an if statement before. We’ll break it down super simply, just like we’ve done in every other chapter. And if you're coming from another programming language! You’ll feel right at home once you see the Bash syntax.

What is Control Flow?

Just like the name says, control flow is all about controlling how your script flows, or in simple terms, deciding what happens next based on certain conditions.

Up until now, our scripts have been doing one thing at a time, step by step. But with control flow, we can make our scripts smarter and more dynamic. Instead of always running the same instructions, our scripts can now react - doing one thing if a condition is true, and something else if it’s not.

At the heart of this concept is the if statement - also called a test statement in Bash. It's a basic but powerful tool that checks for a condition, and based on that, decides what block of code to run.

You’ll find this in pretty much every script out there, because it’s key to making decisions in your code.

Using the If Statement

The if statement - also known as a conditional statement - is a way to run one or more instructions only if a certain condition is true. In Bash, this is often referred to as a test, and it's a core feature you'll see in almost every real-world script.

The basic syntax looks like this:

if given_condition; then
    instructions to execute
fi

Let’s break it down:

  • You start with the keyword if.
  • Then you put the condition you want to check.
  • After that, you use the keyword then.
  • Inside the block, you write all the commands that should run if the condition is true.
  • Finally, you end the block with fi, which is just if spelled backwards. Kinda clever, right?

Let’s see a simple example in action:

year=2025

if [ $year -eq 2025 ]
then
    echo "Yes, it's true"
fi

Here’s what’s happening:

  • We define a variable year and set it to 2025.
  • The if statement checks if $year is equal to 2025 using -eq, which stands for equal.
  • If the condition is true, we print the message "Yes, it's true".
  • If it’s not true, nothing happens.

Now, let’s change the value of the variable and see what happens:

year=2030

if [ $year -eq 2025 ]
then
    echo "Yes, it's true"
fi

If we run this updated script, nothing will be printed. Why? Because the condition is not true, so the echo command gets skipped.

This is the basic idea behind the if statement - check a condition, and do something only if it’s true. Simple, powerful, and super useful.

Using If-Else Statement

If you paid attention to the previous example, we only had one condition to check - and we only did something if that condition was true. But what if we also want to do something when the condition is false?

That's where the else statement comes in. Bash (like most programming languages) gives us this handy tool to handle both sides of a decision.

Here’s the syntax:

year=2030

if [ $year -eq 2025 ]
then
    echo "Yes, it's true"
else
    echo "No, it's false"
fi

We use the keyword else to define what should happen if the condition isn’t true. In this example, the condition checks if the year is 2025. Since it's not, the else block runs and we get:

No, it's false

Now let’s flip it and make the condition true:

year=2025

if [ $year -eq 2025 ]
then
    echo "Yes, it's true"
else
    echo "No, it's false"
fi

If we run this version, the condition is true, so the if block is executed and we’ll see:

Yes, it's true

Simple, right? This is super useful when your script needs to respond to two different possibilities - true or false.

Working with Numeric Values

In the previous example, we compared numbers using Bash. That’s actually a super common thing in scripting - checking if one number is equal to another, or if it’s bigger, smaller, and so on.

We’ve already used one operator: -eq, which means equal to. But Bash gives us several other options when it comes to comparing numbers.

Here’s a quick breakdown:

  • -eq: equal to
  • -ne: not equal to
  • -lt: less than
  • -le: less than or equal to
  • -gt: greater than
  • -ge: greater than or equal to

These work the same way as -eq. You just swap in the operator you need based on the condition you're checking.

Let’s look at an example using -ne, which stands for not equal to:

year=2023

if [ $year -ne 2025 ]
then
    echo "The condition is true"
else
    echo "The condition is false"
fi

Before you run this, pause and think about it. What do you expect to see? Try to guess the output (no peeking!).

Since year is not equal to 2025, the condition is true, so the if block will be executed.

When you run this script, you'll see:

The condition is true

And just like that, your script makes a decision based on a number. Pretty neat, right?

Let’s keep building on this and see how we can work with strings next.

Working with Strings

When it comes to comparing strings in Bash, things work a little differently than when we compare numbers. For numbers, we use operators like -eq or -ne, but for strings, Bash gives us its own set of tools.

Here are some common string comparison operators in Bash:

  • == : checks if two strings are equal
  • != : checks if two strings are not equal
  • < : checks if one string is less than the other (based on alphabetical order)
  • -z : checks if a string is empty
  • -n : checks if a string is not empty

Even though the operators are different, the structure of the if statement stays the same.

Let’s look at a quick example:

name="tecmint"

if [ $name == "tecmint" ]
then
    echo "The condition is true"
else
    echo "The condition is false"
fi

In this case, we’re checking if the value of the name variable is equal to "tecmint". Since it is, the condition is true, and the script will run the commands inside the if block.

The condition is true

Combining Conditions

Sometimes, checking just one thing isn't enough. In the previous examples, we only tested a single condition, but in real-world scripts, you’ll often need to check multiple things at once. That’s where logical operators like AND and OR come into play.

Using the AND Operator

The AND operator lets us check if two or more conditions are true at the same time. If all the conditions are true, then the if block will run. If even one is false, it won’t.

Here’s the basic syntax:

if [ condition1 ] && [ condition2 ]
then
    instructions to execute
fi

Let’s break it down with a simple example. Suppose we want to check if the name is "tecmint" and the tutorial is "bash":

name="tecmint"
tutorial="bash"

if [ $name == "tecmint" ] && [ $tutorial == "bash" ]
then
    echo "The condition is true"
else
    echo "The condition is false"
fi

Since both conditions are true, the script will print:

The condition is true

Now let’s change one of the variables and see what happens:

name="tecmint"
tutorial="linux"

if [ $name == "tecmint" ] && [ $tutorial == "bash" ]
then
    echo "The condition is true"
else
    echo "The condition is false"
fi

This time, even though the name is still "tecmint", the tutorial is "linux", not "bash". So the first condition is true, but the second is false, and because we’re using AND, both need to be true.

Output:

The condition is false

That’s the key idea with && (AND) - every condition must pass for the block to run.

Using the OR Operator

Now let’s flip the scenario. What if we want to check if at least one of the conditions is true, not both? That’s where the OR operator (||) comes in.

Let’s look at an example:

name="tecmint"
tutorial="linux"

if [ $name == "tecmint" ] || [ $tutorial == "bash" ]
then
    echo "The condition is true"
else
    echo "The condition is false"
fi

In this script, we’re checking two things:

  • Is the name equal to "tecmint"?
  • OR is the tutorial equal to "bash"?

If either one of these conditions is true, then the if block will run.

Since name is equal to "tecmint", the condition is considered true - even though the tutorial isn’t "bash".

That’s the power of the OR operator:

Arithmetic Operations in If Statements

Sometimes, you might want to do some math inside your if statements - like adding, subtracting, multiplying, or dividing numbers. That’s what we call arithmetic operations, and the way we do that in Bash is a little different from how we compare strings or basic numbers.

In Bash, to perform arithmetic inside an if statement, we use double parentheses (( )) instead of square brackets.

Here's a simple example:

a=10
b=5

if (( a + b > 20 )); then
    echo "The sum is greater than 20"
else
    echo "The sum is not greater than 20"
fi

Let’s break it down. We create two variables, a and b, and then inside the if statement, we check if the sum of a and b is greater than 20.

Since 10 + 5 is not greater than 20, the else block will run, and you’ll see this output:

The sum is not greater than 20

Now, there’s another way to do the same thing using square brackets, but it’s a bit more verbose:

if [ $((a + b)) -gt 20 ]

Both approaches do the same job.

Just remember this:

  • Use (( )) when you're working directly with arithmetic comparisons.
  • Use [ ] if you're more comfortable with traditional numeric test operators like -eq, -gt, -lt, and so on.

That’s it! Bash gives you a couple of options; use whatever makes more sense to you.

Challenges

Alright, it’s time to level up! Starting from this chapter, we’re introducing challenges to put your skills to the test. These aren’t just random tasks, they’re designed to reflect real-life scenarios you might face as a system administrator or while automating tasks with Bash.

Every chapter moving forward will include one or more challenges to help you apply what you’ve learned. Treat them like mini-projects or puzzles. They're here to sharpen your problem-solving skills and get your hands dirty with actual scripting.

💡
All solutions will be shared at the end of the series. But here's the deal, try solving them on your own first. Don’t ask AI, don’t peek at the answer. Give it a solid shot. You’ll learn way more that way, promise!

Challenge #1

Write a script that takes an input (which will be a number) from the user and checks if the number provided is an even number.

  • If it is, display the message: "The number is even."
  • If not, display the message: "The number is not even."

Hint: We mean by an even number a number that can be divided by two and the remainder is 0.