NASutils Knowledge BaseUnofficialPolski

Bash · lesson 9 of 30 · Decisions and loops · bonusRepeat with loops

for goes over words or counts; while and until test a condition.

Programming on the NAS › Bash in 30 lessons

09-loops.sh Download 09-loops.sh

#!/usr/app/TurboShell/bin/bash
for name in archive media fast; do
  echo "volume $name"
done

for ((i = 1; i <= 3; i++)); do
  printf '%d ' "$i"
done
echo

for i in {10..0..5}; do
  printf '%d ' "$i"
done
echo

left=100
while ((left > 20)); do
  left=$((left / 2))
  echo "half is $left"
done

tries=0
until ((tries == 3)); do
  tries=$((tries + 1))
  ((tries == 2)) && continue
  echo "try $tries"
done

Terminal

$ bash 09-loops.sh
volume archive
volume media
volume fast
1 2 3 
10 5 0 
half is 50
half is 25
half is 12
try 1
try 3

Exercise

Print all even numbers from 2 to 20.