Here is the video version, if you prefer it:
for
loops are used for iterating. Iterating means going over a sequence of values.
Here is an example of a for
loop, modeled after (“Bash For Loop Examples,” n.d.).
#!/bin/bash
for i in 1 2 3 4 5
do
echo $i
done
This will produce the following output:
mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh
1
2
3
4
5
What just happened? The variable i
first took on the value of 1
(the first element in the sequence). Then it echoed its value. Then variable i
took the next value in the sequence (the value after the value it currently had). So i
was 2
. Then 2
got outputted – and so on until the end of the sequence.
You can specify numerical sequences more easily (the above one could have been written as {1..5}
) and you can iterate over other sequences (not just numbers, but other things – files for example). I leave you to consult the reference and Google for some further examples.
Hope you learned something useful!
References
Bash For Loop Examples. (n.d.). Retrieved February 22, 2020, from https://www.cyberciti.biz/faq/bash-for-loop/
Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.