The for loop
The for
loop is one of the used structures when it comes to a Bash script and enables us to repeat one of more actions on each single item in a list. Its basic structure can be outlined as follows:
for placeholder in list_of_items do action_1 $placeholder action_2 $placeholder action_n $placeholderdone
So, we use a placeholder, which will take at each round of the loop one of the values in the list of items, which will then be processed in the do
section. Once all the list is scanned through, the loop is done, and we exit it. Let's start with a simple and nice example:
#!/bin/bash for i in 1 2 3 4 5 do echo "$i"done
And now let's execute it:
zarrelli:~$ ./counter-simple.sh 1 2 3 4 5
Actually, quite straightforward, but notice that the list can be the result of any kind of operations:
#!/bin/bash for i in {10..1..2} do echo "$i"done
In this case, we used a brace expansion to get a countdown with a step of 2:
zarrelli:~$ ./counter-brace.sh 10 8 6 4 2
We can have a for
loop...