Book Image

Linux Shell Scripting Essentials

By : Sinny Kumari, Khem Raj
Book Image

Linux Shell Scripting Essentials

By: Sinny Kumari, Khem Raj

Overview of this book

Table of Contents (15 chapters)
Linux Shell Scripting Essentials
About the Author
About the Reviewers

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]

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

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

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:

# Filename:
# Description: Basic for loop in bash

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

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.