O'Reilly logo

Linux Shell Scripting Essentials by Sinny Kumari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required