for Loops in Shell Script

for Loops in Shell Script

  • for loops allow the repetition of a command for a specific set of values

Syntax:

for var in value1 value2 …
do
command_set
done

  • – command_set is executed with each value of var (value1, value2, …) in sequence

for loop example in shell script

#!/bin/sh
# timestable – print out a multiplication table
for i in 1 2 3
do
for j in 1 2 3
do
value=`expr $i \* $j`
echo -n “$value ”
done
echo
done

For Loop example 2 in shell script

#!/bin/sh
# file-poke – tell us stuff about files
files=
`ls`
for i in $files
do
echo -n “$i ”
grep $i $i
done

  • – Find filenames in files in current directory

#!/bin/sh
# file-poke – tell us stuff about files
for i in *; do
echo -n “$i ”
grep $i $i
done

 

For any query or issue, feel free to discuss on http://discuss.eduguru.in