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, andfi(closing theifblock) 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:
-fchecks if a file exists.- If the file exists, the
echocommand outputs a message about it. If not, theelseblock 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 1sends one request to the server. If it responds, the condition becomes true.&> /dev/nullhides 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 +%Hreturns 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
itakes 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/etcfolder.- On each iteration, the variable
FILEcontains 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 numberGUESSis not equal to the secret numberSECRET.
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
SITEScontains a list of websites. foriterates through each site in the array.ifchecks the site's availability usingping.
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!
GO TO FULL VERSION