BASH cycles

The BASH interpreter supports as many different kind of cycles as true programming language like C or Fortran (see the man page of bash or the "Bash Guide for Beginners" in the "Reference" section to know more); here we will just show a quick example for the most important kind of cycles:

  • iteration over a list of items
$ for i in alfa beta gamma delta
do
echo $i
done

the most common type of iteration is usually applied to the output of some command; in the next example we use the seq command (man seq)

 to print the numbers from 1 to 10 with a nice formatting:
$ for i in `seq -f "%gth" 1 10`
do
echo $i
done
  • C-like for:
$ for((i=0;i<10;i++))
do
echo $i
done
  • while-do:
$ while /bin/true
do
echo 'Hello!'
done
  • until-do:
$ until /bin/false
do
echo 'Hello!'
done

As a last, more complete example, the next cycle prints the first Fibonacci numbers that are smaller than 1000000:

a=1
b=1
while test $a -lt 1000000
do
  let c=$a+$b
  echo $a
  a=$b
  b=$c
done

let is a built-in function of the bash interpreter which let you do simple mathematical operations and save them into a variable.