CodeGym /Courses /Docker SELF /Conditions (`if`, `else`) and loops (`for`, `while`) in b...

Conditions (`if`, `else`) and loops (`for`, `while`) in bash

Docker SELF
Level 3 , Lesson 4
Available

1. Conditions in bash: if, else, and a bit of magic

Why do we need conditions?

Conditions let your script make decisions based on input data, variables, or even the results of commands. For example, you might want to check if a file exists or ensure that a server is accessible before performing the next step. That's where the if construct comes in handy.

Basic syntax

Here's what a typical if condition looks like in bash:

if [ condition ]; then
    # Code runs here if the condition is true
    echo "The condition is true!"
else
    # Code runs here if the condition is false
    echo "The condition is false!"
fi

Key words:

  • if, then, else, and fi (closing the if block) are magic words. Without them, your script won't work.
  • Square brackets [ ... ] are used to check conditions.

Example 1: Checking if a file exists

#!/bin/bash

FILE="/etc/passwd"

if [ -f $FILE ]; then
    echo "The file $FILE exists."
else
    echo "The file $FILE was not found."
fi

Explanation:

  • -f checks if a file exists.
  • If the file exists, the echo command outputs a message about it. If not, the else block runs.

Conditions with commands

You can use the result of a command as a condition because, in Linux, everything is a command.

Example 2: Checking if a website is accessible

#!/bin/bash

if ping -c 1 example.com &> /dev/null; then
    echo "The website is accessible."
else
    echo "The website is not accessible."
fi

Explanation:

  • ping -c 1 sends one request to the server. If it responds, the condition becomes true.
  • &> /dev/null hides the command output to avoid cluttering your terminal.

Using the elif operator

Sometimes if and else aren't enough. You may need to account for multiple conditions. This is where elif comes in.

Example 3: Determining the time of day

#!/bin/bash

HOUR=$(date +%H)

if [ $HOUR -lt 12 ]; then
    echo "Good morning!"
elif [ $HOUR -lt 18 ]; then
    echo "Good afternoon!"
else
    echo "Good evening!"
fi

Explanation:

  • date +%H returns the current hour in 24-hour format.
  • We compare the current time with fixed values: if it's less than 12 — morning, less than 18 — afternoon, otherwise — evening.

2. Loops in bash: practice makes perfect

Loops are a way to make your script repeat actions while a certain condition is met. This is super useful if you need to process a bunch of files, repeat a task several times, or wait for a specific event.

The for loop

for goes through a list of values (e.g., files or numbers) and performs a specified action for each of them.

Example 4: Simple for loop

#!/bin/bash

for i in {1..5}; do
    echo "This is iteration number $i"
done

Explanation:

  • {1..5} — a list of numbers from 1 to 5.
  • On each iteration, the variable i takes a value from the list.

Example 5: Iterating over files in a directory

#!/bin/bash

for FILE in /etc/*; do
    echo "Processing file: $FILE"
done

Explanation:

  • /etc/* — this is the list of all files in the /etc folder.
  • On each iteration, the variable FILE contains the name of one file.

The while loop

while executes actions while a condition is met.

Example 6: Guess the number

#!/bin/bash

SECRET=5
GUESS=0

while [ $GUESS -ne $SECRET ]; do
    echo "Enter your guess (number between 1 and 10):"
    read GUESS
done

echo "You guessed it!"

Explanation:

  • [ $GUESS -ne $SECRET ] — the condition continues as long as the input number GUESS is not equal to the secret number SECRET.

Combining loops and conditions

Sometimes conditions and loops work together.

Example 7: Checking multiple websites

#!/bin/bash

SITES=("example.com" "google.com" "nonexistent.website")

for SITE in ${SITES[@]}; do
    if ping -c 1 $SITE &> /dev/null; then
        echo "$SITE is reachable."
    else
        echo "$SITE is not reachable."
    fi
done

Explanation:

  • The array SITES contains a list of websites.
  • for iterates through each site in the array.
  • if checks the site's availability using ping.

3. Practical exercises

Domain checking

Write a script that takes a domain name as an argument and checks its availability.

Hint:

if ping -c 1 $1 &> /dev/null; then
    echo "Domain is available."
else
    echo "Domain is not available."
fi

Working with files

Write a script that checks the existence of several files and outputs the result for each one of them.

Hint:

FILES=("file1.txt" "file2.txt" "/etc/passwd")
for FILE in ${FILES[@]}; do
    if [ -f $FILE ]; then
        echo "$FILE exists."
    else
        echo "$FILE not found."
    fi
done

Multiplication table

Write a script with nested loops that prints a multiplication table for numbers from 1 to 10.

Hint:

for i in {1..10}; do
    for j in {1..10}; do
        echo -n "$((i * j)) "
    done
    echo ""
done

Now you can start adding some intelligence and logic to your bash scripts. Conditions will let you check states and make decisions, while loops will help automate repetitive tasks. There's so much more automation potential ahead of you!

1
Task
Docker SELF, level 3, lesson 4
Locked
Checking for file existence
Checking for file existence
1
Task
Docker SELF, level 3, lesson 4
Locked
Table of Numbers
Table of Numbers
1
Task
Docker SELF, level 3, lesson 4
Locked
Even and Odd Numbers
Even and Odd Numbers
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION