Looping around with for

The for loop can be used to iterate over the items in a list or till the condition is true.

The syntax of using the for loop in bash is as follows:

for item in [list]
do
   #Tasks
done

Another way of writing the for loop is the way C does, as follows:

for (( expr1; expr2; expr3 ))
  # Tasks
done

Here, expr1 is initialization, expr2 is condition, and expr3 is increment.

Simple iteration

The following shell script explains how we can use the for loop to print the values of a list:

#!/bin/bash
# Filename: for_loop.sh
# Description: Basic for loop in bash

declare -a names=(Foo Bar Tom Jerry)
echo "Content of names array is:"
for name in ${names[@]}
do
   echo -n "$name "
done
echo

The output of the script is as follows:

Content of names array is:
Foo Bar Tom Jerry

Iterating over a command output

We know that a lot of commands give multiline output such as ls, cat, grep, and so on. In many cases, it makes sense to loop over each line of output and do further processing on them.

The following example loops over the content of '/' and prints directories:

#!/bin/bash
# Filename: finding_directories.sh
# Description: Print which all files in / are directories

echo "Directories in / :"
for file in 'ls /'
do
  if [ -d "/"$file ]
  then
     echo -n  "/$file "
  fi
done
echo

The output after running this script is as follows:

Directories in / :
/bin /boot /dev /etc /home /lib /lib64 /lost+found /media /mnt /opt /proc /root /run /sbin /srv /sys /tmp /usr /var

Specifying a range to the for loop

We can also specify a range of integers in the for loop with an optional increment value for it:

#!/bin/bash
# Filename: range_in_for.sh
# Description: Specifying range of numbers to for loop

echo "Numbers between 5 to 10 -"
for num in {5..10}
do
  echo -n "$num "
done

echo
echo "Odd numbers between 1 to 10 -"
for num in {1..10..2}
do
  echo -n "$num "
done
echo

The output after running this script is as follows:

Numbers between 5 to 10 -
5 6 7 8 9 10 
Odd numbers between 1 to 10 -
1 3 5 7 9

Small and sweet for loop

In some cases, we don't want to write a script and then execute it; rather, we prefer to do a job in shell itself. In such cases, it is very useful and handy to write the complete for loop in one line, rather than making it multiline.

For example, printing the multiples of 3 between 3 to 20 numbers can be done with the following code:

$ for num in {3..20..3}; do echo -n "$num " ; done
3 6 9 12 15 18 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.193.37