Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Shell Script - Loops

Bash supports while and for loops. The while loop repeats a block of code as long as a condition is true. The for loop iterates over elements in a list. It can iterate a specific number of times by using expressions. Loops can be nested, with an inner loop executing each iteration of the outer loop.

Uploaded by

Janvi Sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Shell Script - Loops

Bash supports while and for loops. The while loop repeats a block of code as long as a condition is true. The for loop iterates over elements in a list. It can iterate a specific number of times by using expressions. Loops can be nested, with an inner loop executing each iteration of the outer loop.

Uploaded by

Janvi Sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

LOOPS IN SHELL SCRIPTS

Bash supports:
while loop
for loop

a) while loop

The while loop will repeat a chunk of code as long as the given condition is true.

Syntax:

while [ condition ]
do
command1
command2
command3

....
done

Example 1:
i=1
while [ $i -le 10 ]
do
echo “ value of i is $i “
i = ` expr $i + 1 `
done

b) for loop
Syntax 1 :

for { variable name } in { list }


do
execute one for each item in the list until the list is not finished
(And repeat all statement between do and done)
done
Example 1:
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done

Example 2:
count = 0
for i in 2 4 6
do
echo “ i is $i “
count = `expr $count + 1`
done
echo “ the loop was executed $count times”

Discussion :
This for loop will be executed for three times, once with i=2, once with i=4 and
once with i=6.

Syntax # 2:

for (( expr1; expr2; expr3 ))


do
.....
...
repeat all statements between do and
done until expr2 is TRUE
done

Example 1:
for (( i = 0 ; i <= 4; i++ ))
do
echo "Welcome $i times"
done

Output :
Welcome 0 times
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Nesting of for loop
Example:
for (( i = 1; i <= 5; i++ )) ### Outer for loop ###
do
for (( j = 1 ; j <= 5; j++ )) ### Inner for loop ###
do
echo -n "$i "
done
echo "" #### print the new line ###
done

Output:
11111
22222
33333
44444
55555

You might also like