For loop in shell script

By | 24th August 2020

Looping through the list is a very useful and much-needed function for every scripting and programming language. The most common looping method is the programming world is the for loop. In this blog, we will see how to iterate over strings separated by a delimiter in a shell script.

For loop Syntax

for i in ${<Listwithdelimiter>//<Delimiter>/ }; do
    # processing logic
    # processing logic
done

Let us see an example that implements the above syntax. In this example, we will iterate over a string that has values separated by a comma.

ForIterator.sh

sourcestr="Id,name,age,gender,city"

echo "The source string is - $sourcestr"
cnt=0
for i in ${sourcestr//,/ }; do
   let "cnt+=1"
   echo "String $cnt	: $i"
done

The result of the above script upon execution is,

$ sh ForIterator.sh
The source string is - Id,name,age,gender,city
String 1	: Id
String 2	: name
String 3	: age
String 4	: gender
String 5	: city

Also, check “How to read a delimited file in shell

Leave a Reply

Your email address will not be published. Required fields are marked *