CIS120Linux Fundementals
Loops
In Bash scripting, loops are used to repeat a series of commands until a specific condition is met. There are several types of loops available in Bash: for
, while
, and until
loops. These loops can also contain if-else
statements to add conditional logic within the loop.
for Loop
A for
loop iterates over a list of items and executes a block of code for each item.
Syntax:
for var in list; do
# Commands
done
Example:
#!/bin/bash
for num in 1 2 3 4 5; do
echo "Number: $num"
done
This script iterates over the numbers 1 to 5 and prints each number.
while Loop
A while
loop executes a block of code as long as the specified condition is true.
Syntax:
while [ condition ]; do
# Commands
done
Example:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
This script prints the count from 1 to 5.
until Loop
An until
loop is similar to a while
loop but executes the block of code as long as the specified condition is false.
Syntax:
until [ condition ]; do
# Commands
done
Example:
#!/bin/bash
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
This script prints the count from 1 to 5, stopping when the count is greater than 5.
Nesting if-else
Statements in Loops
You can nest if-else
statements within loops to add conditional logic to your loops.
Example with for
Loop:
#!/bin/bash
for num in 1 2 3 4 5; do
if [ $num -eq 3 ]; then
echo "Found three!"
else
echo "Number: $num"
fi
done
In this script, the for
loop iterates over the numbers 1 to 5. When the number is equal to 3, it prints "Found three!" Otherwise, it prints the number.
Example with while
Loop:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
if [ $count -eq 3 ]; then
echo "Found three!"
else
echo "Count: $count"
fi
count=$((count + 1))
done
This script prints the count from 1 to 5. When the count is equal to 3, it prints "Found three!" Otherwise, it prints the count.
Example with until
Loop:
#!/bin/bash
count=1
until [ $count -gt 5 ]; do
if [ $count -eq 3 ]; then
echo "Found three!"
else
echo "Count: $count"
fi
count=$((count + 1))
done
This script prints the count from 1 to 5, stopping when the count is greater than 5. When the count is equal to 3, it prints "Found three!" Otherwise, it prints the count.
Nested Loops
You can also nest loops within other loops to perform more complex iterations.
Example:
#!/bin/bash
for i in 1 2 3; do
for j in a b c; do
echo "Combination: $i$j"
done
done
This script prints all combinations of numbers 1 to 3 with letters a to c.
Summary
Bash provides various looping constructs like for
, while
, and until
loops to perform repetitive tasks efficiently. These loops can be enhanced with nested if-else
statements to introduce conditional logic within the loops. Understanding how to use these loops and conditional statements allows you to write more complex and dynamic Bash scripts.