'How to loop through multiple comma separated strings in shell

I’m trying to loop through multiple comma separated strings with same number of commas in the string.

I’ve tried the below snippet but it doesn’t return anything.

#!/bin/bash
    
ip1=“Ok1,ok2,ok3”
    
ip2=“ty1,ty2,ty3”
    
for i in ${ip[@]//,/} 
do 
        echo $i 
done

Could someone please suggest how I can change this.



Solution 1:[1]

Fixes:

  1. Change ip to ip1 or ip2
  2. Change the smart quotes to regular quotes: ? "
  3. Replace the commas with spaces by adding a space after the final /
ip1="Ok1,ok2,ok3"
ip2="ty1,ty2,ty3"
    
for i in ${ip1//,/ }
do 
        echo "$i"
done

It would be better to use arrays, then the items would be naturally separated and you wouldn't have to do any string manipulation.

ip1=(Ok1 ok2 ok3)
ip2=(ty1 ty2 ty3)
    
for i in "${ip1[@]}"
do 
        echo "$i"
done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Kugelman