Book Image

Linux Shell Scripting Essentials

Book Image

Linux Shell Scripting Essentials

Overview of this book

Table of Contents (15 chapters)
Linux Shell Scripting Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...