Bash loop examples | Linux

Tutorials

When a command or series of commands needs to be repeated, it is put inside a loop. The shell provides three types of loop: while, until, and for. The first two execute until a condition is either true or false; the third loops through a list of words.

while

 

The condition for a while loop is a list of one or more commands, and the commands to be executed while the condition remains true are placed between the keywords do and done:

 

while <list>

do

<list>

done

 

By incrementing a variable each time the loop is executed, the commands can be run a specific number of times:

 

n=1

while [ $n -le 10 ]

do

echo "$n"

n=$(( $n + 1 ))

done

 

The true command can be used to create an infinite loop:

 

while true ## : can be used in place of true

do

read x

done

 

A while loop can be used to read line by line from a file:

 

while IFS= read -r line

do

: do something with "$line"

done < FILENAMEy?

 

 

until

 

Rarely used, until loops as long as the condition fails. It is the opposite of while:

 

n=1

until [ $n -gt 10 ]

do

echo "$n"

n=$(( $n + 1 ))

done

 

 

for

 

At the top of a for loop, a variable is given a value from a list of words. On each iteration, the next word in the list is assigned:

 

for var in Canada USA Mexico

do

printf "%s\n" "$var"

done

 

bash also has a nonstandard form that is similar to that found in the C programming language. The first expression is evaluated when first encountered. The second is a test. The third is evaluated after each iteration:

 

for (( n=1; n<=10; ++n ))

do

echo "$n"

done

 

Since this offers no advantage over standard looping methods, it is not used in this book.

 

 

break

 

A loop can be exited at any point with the break command:

 

while :

do

read x

[ -z "$x" ] && break

done

With a numeric argument, break can exit multiple nested loops:

 

for n in a b c d e

do

while true

do

if [ $RANDOM -gt 20000 ]

then

printf .

break 2 ## break out of both while and for loops

elif [ $RANDOM -lt 10000 ]

then

printf '"'

break ## break out of the while loop

fi

done

done

echo

 

 

continue

 

Inside a loop, the continue command immediately starts a new iteration of the loop, bypassing any remaining commands:

 

for n in {1..9}

do

x=$RANDOM

[ $x -le 20000 ] && continue echo "n=$n x=$x"

done

 

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.