Menu
Coddy logo textTech

If Statement

Part of the Fundamentals section of Coddy's Terminal journey — lesson 70 of 82.

So far, your scripts run every command from top to bottom without any decision-making. But what if you want your script to do different things based on certain conditions? That's where the if statement comes in.

The if statement lets your script make decisions. It checks whether a condition is true, and if so, runs a block of code. Here's the basic structure:

#!/bin/bash
age=18
if [ $age -ge 18 ]; then
    echo "You are an adult"
fi

The condition goes inside square brackets with spaces around it. The then keyword marks the start of the code to run, and fi (if spelled backward) ends the statement.

You can also handle the case when the condition is false using else:

#!/bin/bash
age=15
if [ $age -ge 18 ]; then
    echo "You are an adult"
else
    echo "You are a minor"
fi

Common comparison operators for numbers include -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), -ge (greater or equal), and -le (less or equal). For strings, use = for equality and != for inequality.

Remember to always include spaces inside the brackets and quote your variables to avoid errors with empty values.

challenge icon

Challenge

Easy

Create a shell script called check_score.sh that uses an if statement to evaluate a test score.

Your script should:

  1. Start with the shebang line (#!/bin/bash)
  2. Create a variable called score with the value 75
  3. Use an if statement to check if the score is greater than or equal to 70
  4. If true, print: You passed!
  5. If false, print: You failed.

Make the script executable and run it. Since the score is 75, your output should be:

You passed!

Hint: Remember to use -ge for "greater than or equal to" comparison, include spaces inside the square brackets, and end your if statement with fi.

Cheat sheet

The if statement allows scripts to make decisions based on conditions:

#!/bin/bash
age=18
if [ $age -ge 18 ]; then
    echo "You are an adult"
fi

The condition goes inside square brackets with spaces around it. Use then to mark the start of the code block and fi to end the statement.

Use else to handle cases when the condition is false:

#!/bin/bash
age=15
if [ $age -ge 18 ]; then
    echo "You are an adult"
else
    echo "You are a minor"
fi

Common comparison operators:

  • Numbers: -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), -ge (greater or equal), -le (less or equal)
  • Strings: = (equality), != (inequality)

Always include spaces inside the brackets and quote variables to avoid errors with empty values.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals