In Bash scripting, you can use both for loops and while loops to execute commands repeatedly. Here's a brief explanation of each loop and how to use them:
Syntax:
for variable in [sequence]
do
# commands to be executed
done
Example:
for i in {1..5}
do
echo "Number: $i"
done
This will print numbers from 1 to 5.
Syntax:
while [ condition ]
do
# commands to be executed
done
Example:
counter=1
while [ $counter -le 5 ]
do
echo "Counter: $counter"
((counter++))
done
This will print the value of the counter variable from 1 to 5.
You can also use other conditional statements like break
to exit a loop prematurely or continue
to skip the current iteration and move to the next one.
By combining loops with conditional statements and variables, you can create powerful scripts to automate tasks in Bash.