Jump to content

shell programming for loop

dondasanjay's Photo
Posted Nov 27 2009 08:31 PM
4479 Views

What is the syntax of the "for loop" in the linux shell programming?

Tags:
0 Subscribe


1 Reply

+ 1
  KBenson's Photo
Posted Nov 29 2009 09:55 PM

For bash:

Use double parenthesis to indicate you want ARITHMETIC EVALUATION (see the bash man page) if you are looking for a traditional C-style loop:

$ for ((i=1; i<10; i++)); do echo $i; done
1
2
3
4
5
6
7
8
9
$

Otherwise use the list type:

$ for ITEM in foo bar baz; do echo $ITEM; done
foo
bar
baz
$

Note: multiple expressions can be entered between the "do" and the "done". Think of the expressions in their more stylized forms if this seems odd (the greater thansymbol in inserted by bash when doing multi-line commands, it is not part of the syntax):

$ for ITEM in foo bar baz
> do
> echo $ITEM
> echo "second part of processing loop"
> done
foo
second part of processing loop
bar
second part of processing loop
baz
second part of processing loop

See "Compound Commands" in the bash man page for more info, and more command structures such as while loops, switch statements, if/then branches, and how to define functions.