In Linux bash, the for
loop is used to iterate over a sequence of values. The syntax for a for
loop is:
for variable in list; do commands done
Where variable
is the loop variable, list
is a sequence of values, and commands
are the commands to be executed for each iteration of the loop.
Here is an example of a for
loop that iterates over a list of numbers and prints each number:
for i in 1 2 3 4 5; do echo $i done
This will output the numbers 1 2 3 4 5
.
You can also use the seq
command to generate a sequence of numbers for the for
loop. For example:
for i in $(seq 1 5); do echo $i done
This will have the same effect as the previous example.
You can use the for
loop to iterate over a list of strings, as well. For example:
for word in hello world; do echo $word done
This will output the strings hello
and world
.
The for
loop is a powerful tool for automating tasks and performing operations on multiple items in a list. You can use it in bash scripts or at the command line to iterate over a sequence of values.