How to Loop Through Coma Sperated String in Linux Shell Script


(Bibin Wilson) #1

To loop through comma separated string, you need to use the combination of for loop and sed. There are few ways you can achieve this.

You can add your business logic inside the do done block as shown in the examples below.

Method 1:

hosts="node1,node2"

for i in $(echo $hosts | sed "s/,/ /g")
do
   echo $i
done

Method 2:

variable=node1,node2
for i in ${variable//,/ }
do
  echo "$i"
done