3.1 Loops
Loops are a common programming language feature which allows for iteration over finite collections of data, or a limited or infinite range of indexes. Bash supports the ability to use both of these paradigms and you may choose whichever fits your use-case.
Index-based Loops
To implement a simple index-based for loop, you can use syntax which is largely reminiscent of standard C syntax:
# For all indexes between 0 - 9, print the value
for ((i = 0; i < 10; i++)); do
echo $i
done
A more modern form of this syntax is also supported in the form of ranges. These can function as an effective stand-in for the above pattern, provided that you don’t need more complex conditional checks.
echo -n "Print elements 1 through 5: "
# Loop over all elements between 1 and 5
for i in {1..5}; do
echo -n "$i "
done
echo
echo -n "Print elements 10 through 50 stepping 5 at a time: "
# Loop over elements 10 and 50, stepping 5 at a time.
for i in {10..50..5}; do
echo -n "$i "
done
Iterative Loops
When working with collections, it is also possible to iterate directly over the values present in the array without direct indexing. This can greatly simplify a lot of common loop patterns, and should be preferred whenever indexes are not strictly needed.
# Declare a basic array of multiple values
array=(a 100 we TRUE)
# For each item in the array, print out the corresponding value
for item in ${array[@]}; do
echo $item
done
While Loops
Another common form of loops that Bash supports are while
loops. These loops are better suited for iteration over data sources with no known end point. You can use them in Bash like so:
This will not run properly in the notebook. If you would like to test this out, we recommend you copy this to a local terminal.
while read -l line; do
echo $RANDOM
done
Alternatively, it’s possible to use while
loops to easily create infinite cycles in your script. This can be useful for a number of use-cases including things like perpetual command processing as a simple example.
It is not recommended to run the following code snippet locally as cancelling it becomes annoyingly difficult and will result in wasting of system resources. You can terminate execution by closing this document and re-opening if you run this.
while :
do
echo -n "$RANDOM "
done