How to Use Bash if Statements with Multiple Conditions

ShellShellBeginner
Practice Now

Introduction

This tutorial introduces you to using Bash if statements with multiple conditions to enhance your shell scripting skills. You’ll learn how to combine logical operators effectively, enabling you to build scripts that make smart decisions based on various criteria. By the end of this lab, you’ll be equipped to create versatile automation tools for everyday tasks.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("Shell")) -.-> shell/AdvancedScriptingConceptsGroup(["Advanced Scripting Concepts"]) shell(("Shell")) -.-> shell/SystemInteractionandConfigurationGroup(["System Interaction and Configuration"]) shell(("Shell")) -.-> shell/ControlFlowGroup(["Control Flow"]) shell/ControlFlowGroup -.-> shell/if_else("If-Else Statements") shell/ControlFlowGroup -.-> shell/cond_expr("Conditional Expressions") shell/AdvancedScriptingConceptsGroup -.-> shell/read_input("Reading Input") shell/SystemInteractionandConfigurationGroup -.-> shell/exit_status_checks("Exit Status Checks") subgraph Lab Skills shell/if_else -.-> lab-413763{{"How to Use Bash if Statements with Multiple Conditions"}} shell/cond_expr -.-> lab-413763{{"How to Use Bash if Statements with Multiple Conditions"}} shell/read_input -.-> lab-413763{{"How to Use Bash if Statements with Multiple Conditions"}} shell/exit_status_checks -.-> lab-413763{{"How to Use Bash if Statements with Multiple Conditions"}} end

Understanding the Basics of Bash if Statements

Let’s start with the foundation. In Bash, the if statement helps your script decide what to do based on whether a condition is true or false. This is especially useful when you need to automate tasks on your Ubuntu system.

Open your terminal in the default directory, /home/labex/project. You’ll write all your scripts here. To begin, create a simple script file named basic_if.sh by typing:

touch basic_if.sh

Add the following code to check if a file exists:

#!/bin/bash
if [[ -f "testfile.txt" ]]; then
  echo "The file exists."
else
  echo "The file does not exist."
fi

This script uses [[ -f "testfile.txt" ]] to test if testfile.txt exists in your current directory. The echo command will display a message depending on the result.

To run the script, make it executable:

chmod +x basic_if.sh

Then execute it:

./basic_if.sh

Since testfile.txt doesn’t exist yet, you’ll see "The file does not exist." Let’s create the file to see the other outcome:

touch testfile.txt

Run the script again:

./basic_if.sh
basic_if.sh

Now, it should output "The file exists." This step introduces you to the basic structure: if, then, else, and fi. The double brackets [[ ]] are a modern Bash feature, making condition testing more reliable than single brackets.

Adding Multiple Conditions with AND (&&)

Now, let’s make your if statement smarter by checking multiple conditions at once. You’ll use the && (AND) operator, which requires all conditions to be true for the then block to run.

Open basic_if.sh again and replace its contents with this updated script:

#!/bin/bash
if [[ -f "testfile.txt" ]] && [[ -r "testfile.txt" ]]; then
  echo "The file exists and is readable."
else
  echo "The file is either missing or not readable."
fi

This script checks two things: if testfile.txt exists (-f) and if it’s readable (-r). Both must be true for the first message to appear.

Run the script:

./basic_if.sh

Since you created testfile.txt in Step 1 and it’s readable by default (as labex owns it), you’ll see "The file exists and is readable." To understand how && works, let’s test the opposite scenario. Change the file’s permissions to make it unreadable:

chmod u-r testfile.txt

Run the script again:

./basic_if.sh

Now, it outputs "The file is either missing or not readable" because the second condition (-r) fails. Restore readability for the next steps:

chmod u+r testfile.txt

The && operator ensures that every condition must pass—perfect for situations where multiple criteria matter.

Using OR (||) for Flexible Conditions

Next, you’ll explore the || (OR) operator, which lets the then block run if at least one condition is true. This is useful when you want flexibility in your checks.

Open basic_if.sh again. Update it with this code:

#!/bin/bash
if [[ -f "testfile.txt" ]] || [[ -f "backup.txt" ]]; then
  echo "At least one file exists."
else
  echo "Neither file exists."
fi

This script checks if either testfile.txt or backup.txt exists. Since testfile.txt is already in your directory, run it:

./basic_if.sh

You’ll see "At least one file exists." Now, remove testfile.txt to test the || logic:

rm testfile.txt

Run the script again:

./basic_if.sh

It outputs "Neither file exists" because neither file is present. Create backup.txt to see the OR condition succeed:

touch backup.txt
./basic_if.sh

Now, it says "At least one file exists" again. The || operator is great when any one condition being true is enough.

Combining AND and OR Operators

Let’s combine && and || for more complex logic. You’ll check if a file exists and meets specific criteria, with a fallback condition.

Open basic_if.sh again. Update it with this code:

#!/bin/bash
if [[ -f "testfile.txt" ]] && [[ -r "testfile.txt" ]] || [[ -f "backup.txt" ]]; then
  echo "Either testfile.txt is readable or backup.txt exists."
else
  echo "No suitable file found."
fi

This script checks if testfile.txt exists and is readable, or if backup.txt exists. Recreate testfile.txt:

touch testfile.txt

Run the script:

./basic_if.sh

It outputs "Either testfile.txt is readable or backup.txt exists" because testfile.txt meets both conditions. Remove testfile.txt and keep backup.txt:

rm testfile.txt
./basic_if.sh

The same message appears because backup.txt satisfies the || condition. Remove backup.txt too:

rm backup.txt
./basic_if.sh

Now, it says "No suitable file found." This step shows how to mix operators for nuanced decisions.

Applying Conditions to a Practical Task

Finally, let’s use what you’ve learned in a real-world scenario: validating user input. You’ll write a script to check if a number is within a range.

Create a new script called number_check.sh:

touch number_check.sh
chmod +x number_check.sh

Add this code:

#!/bin/bash
read -p "Enter a number between 1 and 10: " number
if [[ "$number" -ge 1 ]] && [[ "$number" -le 10 ]]; then
  echo "Valid number: $number"
else
  echo "Invalid number. Please enter a value between 1 and 10."
fi

This script prompts you to enter a number, then uses && to ensure it’s between 1 and 10 (inclusive). Run it:

./number_check.sh

Type 5 and press Enter. You’ll see "Valid number: 5". Run it again and enter 15. It responds with "Invalid number. Please enter a value between 1 and 10." This is a practical way to handle user input, ensuring your script only proceeds with valid data.

Summary

In this lab, you’ve mastered Bash if statements with multiple conditions using && and || operators. From checking file properties to validating user input, you’ve built scripts that make decisions based on complex criteria. These skills enable you to create reliable automation tools tailored to various needs on your Ubuntu system.