2

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.

1
  • 1
    You seem to be using ip as if it were an array. But ip1 and ip2 are strings, so ${ip[@]} is probably not what you think it is. Commented Mar 1, 2022 at 14:14

2 Answers 2

4

Replace the comma-separated string with an array as soon as feasible. If it's a hard-coded string, that's trivial:

ip1=(Ok1 ok2 ok3)

If it's from an external source (say, a command-line argument or read from a file), use read:

ip1s="Ok1,ok2,ok3"
IFS=, read -a ip1 <<< "$ips1"

Once you have an array, you can use array syntax for iteration:

for i in "${ip1[@]}"; do
    echo "$i"
done

If you have multiple arrays you want to iterate in lockstep, you can iterate over the keys of the arrays:

for i in "${!ip1[@]}"; do
  echo "${ip1[i]}"
  echo "${ip2[i]}"
done

(This ignores the possibility of sparse arrays, but you have to work to get those. In practice, arrays with n elements usually have keys 0, 1, ... n-1.)

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.