You are currently viewing Loop statement in bash or shell script

Loop statement in bash or shell script

Loop statement in bash or shell script 

loop in bash, if ever we want to do some task repeatedly then we use loop statement in bash script.

We have following loop in bash script

for loop
while loop
until loop

for loop in bash

for value in parameter1 parameter2 parameter3
do
Statements or commands
done

Example

#!/bin/bash

for i in 1 2 3 4 5
do
echo "$i"
done
#!/bin/bash

for Cources in ccna ccnp bashScript
do
echo $Cources 
done

Also we can use below syntax

for arg in [list]
do
command(s)
done

If do is on same line as for, there needs to be a semicolon after list.

for arg in [list] ; do
command(s)
done

Bash for loop range

example

#!/bin/bash
for Num in {1..10}
do
echo "$Num "
done

output

1
2
3
4
5
6
7
8
9
10

Bonus Example

From below script we will fetch all the users on the system

#!/bin/bash

PASSWORD_FILE=/etc/passwd

setNum=1 # setting initial value
for name in $(awk 'BEGIN{FS=":"}{print $1}' < "$PASSWORD_FILE" )

do
echo "USER #$setNum = $name"
let "setNum += 1"
done
exit $?

Output

USER #1 = root
USER #2 = daemon
USER #3 = bin
USER #4 = sys
USER #5 = sync
USER #6 = games
USER #7 = man
USER #8 = lp
USER #9 = mail
USER #10 = news
USER #11 = uucp
USER #12 = proxy
USER #13 = www-data

Bash while loop

Bash while loop first  tests for a condition at the top of a loop, and keeps looping as long as that condition is true (returns a 0 exit status).

syntax

while [ Check for condition ]
do
Statements or commands
done

OR

Its always required semicolon while we use do keywords  on the same line with while keywords

while [ condition ] ; do
Statement
done

Simple while loop Example

#!/bin/bash
Num=0
LIMIT=10
while [ "$Num" -lt "$LIMIT" ]

do
echo "$Num" 

Num=`expr $Num + 1` # this is for incresing counter vale by 1 every time
# Num=$((Num + 1)) also works.
# let "Num += 1" also works.
done

Output

0
1
2
3
4
5
6
7
8
9

Bash Until loop

Until loop tests for a condition at the top of a loop, and keeps looping as long as that condition is false (opposite of while loop).

until [ condition-is-true ]
do
Statements
done

OR

until [ condition-is-true ] ; do
Statements
done

Example of Until loop

#!/bin/sh
Num=0
until [ ! $Num -lt 10 ]
do
echo $Num
Num=`expr $Num + 1`
done

Output

0
1
2
3
4
5
6
7
8
9

Break, Continue in bash script

The break command terminates the loop (breaks out of it), while continue causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle.


You May Also Enjoy Reading This …

Leave a Reply