For loop in Shell Scripting



For loop is used for looping a range of values, which can be any set of strings.

Syntax for loop

for variable in values
do
statements
done


During each pass through the loop, variable takes on the value of each successive variable in the values.


Example

#!/bin/sh
for var in page linux dot com
do
echo $var
done
exit 0


We get the output:

page
linux
dot
com


How it works
Here a variable var is created and defines a different values in each loop. First time it assigns value page, for next loop next value linux is assigns for var and so on.



Using for loop for counting till 10 in different ways.

#!/bin/bash
for a in 1 2 3 4 5 6 7 8 9 10
do
echo -n "$a "
done
echo
exit 0


#!/bin/bash
for a in `seq 10`
do
echo -n "$a "
done
echo
exit 0


#!/bin/bash
for ((a=1; a <= 10 ; a++))
do
echo -n "$a "
done
echo
exit 0



Use double bracket after for in last example.


Use -n option after echo for display output in same line. Without  -n option each output will print on display in new line.




No comments: