05/02/2026
Working with 'for' Loop in Linux!
In Linux Bash scripting, the for loop is used to repeat a set of commands for every item in a list (like a list of files, numbers, or strings).
1. The Basic Syntax: The loop iterates through a list of items, assigning the current item to a variable each time.
for variable in item1 item2 item3; do
# Commands to run
echo "Processing $variable"
done
Key Components:
* variable: A placeholder name (often i, file, or name).
* in: Specifies the list of items to loop through.
* do ... done: The block of code that repeats.
2. Common Examples:
A. Loop Over a List of Strings:
#!/bin/bash
for color in Red Green Blue; do
echo "The color is $color"
done
B. Loop Over a Range of Numbers:
There are two common ways to do this in Bash.
Method 1: Brace Expansion (Easiest)
Best for simple sequences.
for i in {1..5}; do
echo "Number: $i"
done
Method 2: C-Style Syntax
Best if you need custom steps (like increasing by 2) or complex logic.
for (( i=0; i
for i in {1..10}; do
if [ "$i" -eq 5 ]; then
continue # Skip number 5
fi
if [ "$i" -gt 8 ]; then
break # Stop loop after 8
fi
echo "Number: $i"
done
4. The One-Liner: If you are working directly in the terminal, you can write loops on a single line using semicolons:
for i in {1..3}; do echo "Count $i"; done