Loops
Bash loops come in the general format for / do / done
. They also support break
and continue
statements, which break out of the loop and skip to the next iteration, respectively.
C-style loops
Bash supports C-style loops, with an initializer expression, a conditional expression, and a counting expression:
for (( i=0; i<=9; i++ ))
do
echo "Loop var i is currently $i"
done
for…in
Let’s talk about iteration with for...in
loops. Try running the following in your shell:
for i in 1 2 3 4 5
do
echo $i
done
Here’s a loop with some control flow inside:
for os in FreeBSD Linux NetBSD "macOS" DragonflyBSD
do
echo "Checking out ${os}..."
if [[ "$os" == 'NetBSD' ]]; then
echo "(I'm pretty sure this would run on my toaster, actually)"
fi
sleep 1
done
While
Another common control structure you might be familiar with from other programming languages...