top of page
Loops in Linux Shell Scripts
Write efficient loops for automation in shell scripts.
Loops allow you to execute a set of statements n number of times. Generally a loop re-runs a series of statements until a situation or condition is true.
For Loop in Linux
A simple FOR loop defines how many times you would like to run piece of code
#!/bin/bash
for i in {1..5}
do
echo "Hello World"
done
The above FOR LOOP will execute for 5 times. Here i is just a variable (you can use any variable) and {1..5} defines how many times we would like to execute code between do and done.
Break Loop
To break a loop in-between and exit out, we use BREAK command. The below loop will exit when i is 2
#!/bin/bash
for i in {1..5}
do
if [ $i -eq 2 ]; then
break
else
echo "Hello World"
fi
done
🐼🐼🐼
bottom of page