30. Loops: for and while Loops for Repetitive Tasks
Loops are essential for automating tasks that need to be performed multiple times, such as processing a list of files or repeating until a condition is met.
1. The for Loop (Iterating over a list)
The for loop iterates over a defined list of items (words, files, numbers).
Syntax:
bash for VARIABLE in LIST_OF_ITEMS; do # Commands using $VARIABLE done
Example: Processing Log Files
bash #!/bin/bash
LOGS=$(ls *.log)
for logfile in $LOGS; do echo "Processing $logfile..." # Example: Check the last line of the log tail -n 1 $logfile done
2. The while Loop (Repeating until Condition is False)
The while loop continues executing commands as long as the condition remains true.
Syntax:
bash while [ condition ]; do # Commands done
Example: Countdown Timer
bash #!/bin/bash
COUNTER=5
while [ $COUNTER -gt 0 ]; do echo "$COUNTER seconds remaining..." sleep 1 # Wait for 1 second COUNTER=$((COUNTER - 1)) done
echo "Time's up!"
(Note: $(( )) is used for arithmetic operations in Bash.)