Contents / Previous / Next


Loops

With loops you can repeat a statement multiple times.

while and until

The number of repetitions depends on some conditional statement.
Example "count to 10" ( -le stands for less than or equal): N=1 while test "$N" -le "10" do echo "Number $N" N=$[N+1] done

The until statement is identical to while
except that the reverse logic is applied.

For Loops

"For" loops over a command block between do and done
and replaces the loop variable with elements from a list.

The elements can be strings (e.g., file names) or numbers. for i in cows sheep chickens pigs do echo "$i is a farm animal" done echo -e "but\nGNUs are not farm animals"

Looping Over Glob Expressions

The shell can expand file names when given
wildcards (ls *.txt).
This applies equally well in any situation: #!/bin/sh for i in *.txt ; do echo "found a file:" $i done

Loop through each command-line arguments

for i in $1 $2 $3 $4 ; do <statments> done The shift Keyword offers more flexibility:
It shifts up all the arguments by one place so that $1
gets the value of $2, $2 gets the value of $3, and so on. while test "$1" != "" ; do echo $1 shift done Note: $0 is immune to shift operations.