For-loops (Bash)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

Er zijn verschillende manieren om een for-loop te doen. Een bloemlezing:

Ranges

It seems that any kind of range can be used as an argument for a loop. E.g.:

  • Arrays
  • Indices of arrays
  • seq-ranges
  • {}-ranges
  • ``-ranges

In this article, they might all be discussed as separate loop mechanisms.

{} - Range

Gebruik van een for-loop met een range:

declare -A tr
#
tr[1,1]="Eén";	tr[1,2]="Jeden"
tr[2,1]="Twee";	tr[2,2]="Dwa"

for i in {1..2}
do
   echo ${tr[$i,1]}" - " ${tr[$i,2]}
done

This works fine with a fixed range. You cannot use variables, so this doesn't work:

START=1
END=5
for i in {$START..$END}
do
   echo "$i"
done

Array values

Interesting: A range doesn't have to be a sequence of monotoneously increasing values. It can be anything - Including the values of the entities that make up an array:

mapfile -t j < <( wp --user=4 wc product_attribute_term list 20 --field=id )
echo "Array j: ${j[@]}"
echo "All indices: ${!j[@]}"

for i in ${j[@]}
do
   echo $i
done

Array index range

Since arrays can be used for loops, indices can surely be used:

mapfile -t j < <( wp --user=4 wc product_attribute_term list 20 --field=id )
echo "All entries: ${j[@]}"
echo "All indices: ${!j[@]}"

echo "Loop over array index:"
for i in ${!j[@]}
do
   echo $i
done

Just a number - Doesn't work

array_rows=12

for i in $array_rows
do
   echo $i
done

The only output will be 12 - There won't be any loop. So, just giving a number as argument for a loop, doesn't work.

Three-parameter loops - C-style loops

Three-parameter loops oftewel C-style loops kunnen een oplossing zijn voor bv. range-loops met variabele range:

Het for-keyword kent drie argumenten:

  1. Startwaarde
  2. Conditie
  3. Waardeverandering.

Voorbeeld:

i=1
for ((i; i<=10; i++))
do
   echo $i
done

Uitvoer:

1
2
3
4
5
6
7
8
9
10

Maw.: De increment vindt plaats na de loop.

Ander voorbeeld:

for ((i=0; i < $number_of_threads; i++))
do
   ...
done

Seq - Range

You can generate a sequence of numbers with seq to be used in a loop. E.g.:

$ for i in $(seq 3); do echo $i; done

1
2
3

Use $() or `...` to evaluate the seq-statement before executing the loop.

Including a step:

$ for i in `seq 0 2 6`; do echo $i; done

0
2
4
6

Step

Loops can often be extended with a step function. E.g.:

$ for i in `seq 0 2 10`; do echo $i; done

0
2
4
6
8
10

Zie ook