Lesson 16 of 17
Loops
Repeating Commands
Shell loops let you run commands multiple times — over a list of values, over files, or until a condition changes.
The for Loop
The most common loop iterates over a list:
for i in 1 2 3; do
echo "Number $i"
done
Output:
Number 1
Number 2
Number 3
Structure:
for VARIABLE in LIST; do— starts the loopCOMMANDS— body (can be multiple lines)done— ends the loop
The variable (i) takes each value from the list in turn.
Iterating Over Files
for file in *.txt; do
echo "Found: $file"
done
The *.txt glob expands to all .txt files in the current directory.
Iterating Over a Range
for i in $(seq 1 5); do
echo "$i"
done
Or with brace expansion (bash):
for i in {1..5}; do
echo "$i"
done
The while Loop
while runs as long as a condition is true:
COUNT=1
while [ $COUNT -le 3 ]; do
echo "Count: $COUNT"
COUNT=$((COUNT + 1))
done
Your Task
Write a for loop that prints Number 1, Number 2, and Number 3 on separate lines.
Linux shell loading...
Loading...
Click "Run" to execute your code.