Mastering Shell Loops: From Basic for to Advanced Nested and Infinite Loops
This guide explains the essential loop constructs in Bash—basic for loops, range expansions, while loops, nested loops, dynamic iteration over system data, variable validation techniques, file line processing, and infinite loops—providing clear examples and practical code snippets for each scenario.
Basic for Loop
The simplest loop in a shell script is the for loop. List the values after in and the loop iterates over them:
#!/bin/bash
for num in 1 2 3 4
do
echo $num
doneTo iterate over a sequence of letters or numbers, use brace expansion:
#!/bin/bash
for x in {a..z}
do
echo $x
donewhile Loop
The while loop evaluates its condition before each iteration. It is useful when the number of iterations is not known in advance or when the loop may run many times.
#!/bin/bash
n=1
while [ $n -le 4 ]
do
echo $n
((n++))
doneNested Loops
Loops can be nested just like in other programming languages. The example below nests a for loop inside a while loop to produce combinations of numbers and letters:
#!/bin/bash
n=1
while [ $n -lt 6 ]
do
for l in {a..d}
do
echo $nl
done
((n++))
doneThe output will be 1a 1b 1c 1d 2a … 5d.
Dynamic Loop Content
When the values to iterate over are not known beforehand, you can generate them with commands. For example, list all users on the system:
#!/bin/bash
for user in `ls /home`
do
echo $user
doneOr retrieve the current date and iterate over its words:
$ for word in `date`
> do
> echo $word
> done
Thu
Apr
9
08:12:09
CST
2020Variable Value Checks
When using a while loop that depends on a numeric variable, you often need to verify that the input is a number. Three common methods are:
Arithmetic comparison with -eq (numeric only).
Shell pattern matching using *[[:digit:]]*.
Regular‑expression match with [[ $var =~ ^[0-9]+$ ]].
Example combining input validation with a loop:
#!/bin/bash
echo -n "How many times should I say hello? "
read ans
if [ "$ans" -eq "$ans" ]; then
n=1
while [ $n -le $ans ]
do
echo hello
((n++))
done
fiReading a Text File Line by Line
To process a file line by line, read the filename from the user and use a while read loop with input redirection:
#!/bin/bash
echo -n "File> "
read file
n=0
while read line; do
((n++))
echo "$n: $line"
done < $fileInfinite (Dead) Loop
For tasks that should run continuously, use an infinite while true loop:
#!/bin/bash
while true
do
echo -n "Still running at "
date
sleep 1
doneThis script prints the current time every second until interrupted with Ctrl+C.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
