Shell Script Loops Explained
1. For Loop:
Syntax:
for var in word1 word2 ... wordN
do
# Commands to execute for each word
done
How it works:
- A for loop iterates through a list of words (or numbers, files, etc.), assigning each value to the variable var
- Useful when you know the range or set of items beforehand.
Example:
#!/bin/bash
echo "Printing numbers from 1 to 5:"
for num in 1 2 3 4 5
do
echo $num
done
Output:
Printing numbers from 1 to 5:
3
4
---------------------------------------------------
2. While Loop:
Syntax:
while command
do
# Commands to execute while the command is true
done
How it works:
- A while loop keeps executing as long as the given command or condition evaluates to true.
- Useful when you do not know in advance how many iterations are needed.
Example:
#!/bin/bash
num=1
echo "Printing numbers from 1 to 5 using while loop:"
while [ $num -le 5 ]
do
echo $num
num=$((num + 1)) # Increment the counter
done
Output:
Printing numbers from 1 to 5 using while loop:
---------------------------------------------------
3. Until Loop:
Syntax:
until [ condition ];
do
# Commands to execute until the condition becomes true
done
How it works:
- An until loop is the opposite of a while loop: it keeps running as long as the condition is false and stops wh
- Useful for tasks where you need to wait for a condition to become true.
Example:
#!/bin/bash
num=1
echo "Printing numbers from 1 to 5 using until loop:"
until [ $num -gt 5 ]
do
echo $num
num=$((num + 1)) # Increment the counter
done
Output:
Printing numbers from 1 to 5 using until loop:
---------------------------------------------------
4. Select Loop:
Syntax:
select var in word1 word2 ... wordN
do
# Commands to execute for each word
done
How it works:
- A select loop is used to create simple menus.
- It displays a numbered list of items and waits for the user to select an option by entering the correspondin
- Very useful for creating interactive scripts.
Example:
#!/bin/bash
echo "Choose a programming language:"
select lang in Python Java C++ Bash
do
echo "You selected: $lang"
break # Exit after the first selection
done
Output:
1) Python
2) Java
3) C++
4) Bash
#? 2
You selected: Java
---------------------------------------------------
Summary of Use Cases:
| Loop | Use Case |
|--------------|---------------------------------------------------------|
| For Loop | Predefined list of items to iterate through |
| While Loop | Repeat as long as a condition is true |
| Until Loop | Repeat until a condition becomes true |
| Select Loop | Create menus or prompt the user to choose an option |