Now then, the first loop we will learn is the "for." This is a simple one. This will execute the command lines that you put inside it for every value inside a list. The syntax is simple:
for i in list
do
command line
...
done
Inside the loop we can use $i to refer to the current item in the list. This way $i will get all the values, one after another, inside the list. The list is optional; we can choose to add no specific list. Now the loop will look like this:
for i
do
command line
...
done
If this is the case, then the $i will iterate through the arguments of the script. Therefore, we can conclude that, by default, a loop will iterate through the $@ special variable, containing a list of the variables. Here is a simple usage of this, showing how to echo back all the arguments of a script/shell program:
for i
do
echo "$i"
done
The list may be explicit also, as in the example below:
for i in alfa beta omega
do
ls $i 2>/dev/null
done
This will list the content of the directories alfa, beta and omega, if they exist. If we want to iterate through a sequence, we can use the seq command to generate one. This will have as arguments from where, in which steps, and until where to generate the sequence.
for i in $( seq 1 2 10)
do
echo $i
done
This will print out 1, 3, 5, 7, and 9 to the terminal. Of course, we can use the $() syntax to store any list of items, and to iterate through those with the "for" loop. For example, iterating through the items inside the working directory looks like this:
for i in $( ls )
do
if [ "$i" -x ]
then
echo You can execute "$i"
fi
done
It is important to note that the bash here will call the original ls function, and not the ls alias that returns color signaling. This way, it will not interfere with our work.