Bash loops

From wikinotes
Revision as of 22:52, 29 October 2022 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Loop Control

continue  # skip to next iteration
break     # stop looping

Loop Types

for loop

for item in array

list=(a b c d)

for ch in ${list[@]};do
    echo -n $ch
done
#> a b c d

for index in array

list=(a b c d)
for i in "${!list[@]}"; do
  echo "$i == ${list[$i]}"
done

for i in expr

for (( i=0; $i < 4; i++ )); do
   echo -n "$i"
done
#> 0 1 2 3

for num in range

for i in $(seq 0 3); do
    echo -n "$i "
done
#> 0 1 2 3

iterate array by two

gitcmd=(
	"bash"   "/home/will/progs/bash"
	"config" "/home/will/progs/config"
)

for (( i=0; $i < ${#gitcmd[@]}; i=(( $i+2 )) )); do
	echo ${gitcmd[$i]}
done

while loop

while [ $x -le 5 ]; do
    echo $x
    x=$(( $x + 1 ))
done
while true; do
  echo "hi"
done

while read loop

This is useful for iterating over items with spaces.

find . | while read f; do
    echo "--$f";
done

until loop

until [ "$var1" == "2" ] ; do
   echo 'repeat until $var1 == 2'
done

read loop (iterate lines)

Iterate over lines (may contain spaces)

find . | while read -r var; do
  echo "$var"
done