Linux Bash Shell: 10 For Loop Examples

Linux Bash Shell: 10 For Loop Examples

The following are ten examples of Linux for loop using bash shell scripting.

1. Iterate between a range of numbers

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

Output

1
2
3
4
5
6
7
8
9
10

2. Loop until reach given value

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

Output

1 2 3 4 5 6 7 8 9 10 $

3. Loop through a specific range of numbers hardcoded

#!/bin/bash
for nvar in 11 12 13 14 15 16 17 18 19 20
do
   echo $nvar 
done

4. Loop and print all the parameters passed to the script

#!/bin/sh
for nvar in $*
do
   echo "Parameter contains: $nvar"
done

Test

./for4.sh one two three

Output

Parameter contains: one
Parameter contains: two
Parameter contains: three

5. Read a text file word by word

#!/bin/bash
# create a text file named textfile.txt and put some content
# India Singapore Hong Kong United Kingdom
for cvar in `cat textfile.txt`
do
   echo "cvar contains: $cvar"
done

Output

cvar contains: India
cvar contains: Singapore
cvar contains: Hong
cvar contains: Kong
cvar contains: United
cvar contains: Kingdom

6. Read the contents of a directory

#!/bin/bash
echo -n "Contents of the directory are : $var"
for var in $(ls ./*)
do
echo "$var"
done

Output

./album.sh
./busy.sh
./calc.sh

7. Read a list of files to make a backup copy

#!/bin/bash
for filename in *.sh
do
   echo "Copying $filename to $filename.bak"
   cp $filename $filename.bak
done

8. Loop with Continue statement

#!/bin/bash
for var in 1 2 3
do
	echo before $var
	continue
	echo after $var
done
exit 0

Output

before 1
before 2
before 3

9. Ask for input to display the square of a number until 0

#!/bin/bash
typeset -i num=0
while true
do
echo -n "Enter any number (0 to exit): "
read num junk
if (( num == 0 ))
then
break
else
echo "Square of $num is $(( num * num ))."
fi
done
echo "script has ended"

Output

Enter any number (0 to exit): 8
Square of 8 is 64.
Enter any number (0 to exit): 15
Square of 15 is 225.
Enter any number (0 to exit): 6
Square of 6 is 36.
Enter any number (0 to exit): 0
script has ended

10. Loop for specified number values with sorting

#!/bin/bash
for value in 9 3 17 22 15 23
do
   echo $value
done | sort -n

Output

3
9
15
17
22
23

See also