Shell_Script_Loops_Explained
Shell_Script_Loops_Explained
1. For Loop:
Syntax:
do
done
How it works:
- A for loop iterates through a list of words (or numbers, files, etc.), assigning each value to the variable var
Example:
#!/bin/bash
for num in 1 2 3 4 5
do
echo $num
done
Output:
3
4
---------------------------------------------------
2. While Loop:
Syntax:
while command
do
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
do
echo $num
done
Output:
Printing numbers from 1 to 5 using while loop:
---------------------------------------------------
3. Until Loop:
Syntax:
until [ condition ];
do
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
do
echo $num
num=$((num + 1)) # Increment the counter
done
Output:
---------------------------------------------------
4. Select Loop:
Syntax:
do
done
How it works:
- It displays a numbered list of items and waits for the user to select an option by entering the correspondin
Example:
#!/bin/bash
echo "Choose a programming language:"
do
done
Output:
1) Python
2) Java
3) C++
4) Bash
#? 2
---------------------------------------------------
|--------------|---------------------------------------------------------|