Bash Loop Basics
Understanding Bash Loops
In Bash scripting, loops are fundamental control structures that allow you to repeat a set of commands multiple times. There are three primary types of loops in Bash:
for
loops
while
loops
until
loops
For Loops
for
loops are used to iterate over a list of items or a range of values. Here's a basic syntax:
for variable in list
do
commands
done
Example:
#!/bin/bash
for fruit in apple banana cherry
do
echo "I like $fruit"
done
While Loops
while
loops execute commands as long as a condition is true:
while [ condition ]
do
commands
done
Example:
#!/bin/bash
counter=0
while [ $counter -lt 5 ]
do
echo "Counter is $counter"
((counter++))
done
Until Loops
until
loops are the opposite of while
loops, executing until a condition becomes true:
until [ condition ]
do
commands
done
Example:
#!/bin/bash
count=0
until [ $count -eq 5 ]
do
echo "Count is $count"
((count++))
done
Loop Control Structures
Bash provides two important control statements within loops:
Statement |
Purpose |
Usage |
break |
Exit the current loop |
Immediately terminates loop execution |
continue |
Skip current iteration |
Moves to next iteration of the loop |
Break Example
#!/bin/bash
for i in {1..10}
do
if [ $i -eq 6 ]
then
break
fi
echo $i
done
Continue Example
#!/bin/bash
for i in {1..5}
do
if [ $i -eq 3 ]
then
continue
fi
echo $i
done
Nested Loops
Bash also supports nested loops, allowing more complex iteration patterns:
#!/bin/bash
for i in {1..3}
do
for j in {A..C}
do
echo "$i-$j"
done
done
By mastering these loop basics, you'll be well-equipped to write more efficient and powerful Bash scripts in your LabEx programming environment.