I am trying to convert a string into an array and loop that array to pass each value as a parameter to a bash command. I am getting bad substitution message when I execute the scripts.

text = 'xdc','cde','erd','ded','ded','kie';
for (i=0; i<${#ids[@]}; ++i);
echo "$i"

This the script I have written, also how to pass the index value as a parameter to a command inside the for loop.

  • What do you mean by using the array index value as a parameter? Can you give an example?
    – Arronical
    Aug 11, 2016 at 11:54

2 Answers 2


First, you need to remove the text from around the assignment of the string variable:


Then you can just use the array form of the bash read command:

IFS=, read -a ids <<< "${text%;}"

where the ${text%;} substitution removes the trailing semicolon. Note that, this way, the IFS is not modified outside of the read command so there's no need to save and restore it.

Your C-style for-loop syntax is almost correct, except that in bash, the loop needs double parentheses e.g.

for ((i=0; i<${#ids[@]}; ++i)); do printf '%s\n' "${ids[i]}"; done

Alternatively, you can loop over array members directly using a for ... in loop:

for i in "${ids[@]}"; do printf '%s\n' "$i"; done
  • thanks for your answr.. I tried the above but i get Bad substitution
    – Jes
    Aug 11, 2016 at 15:03
  • @Jes which line specifically gives the bad substitution? are you sure you are running the everything with bash not sh? Aug 11, 2016 at 15:08
  • for i in "${ids[@]}"; do printf '%s\n' "$i"; done
    – Jes
    Aug 11, 2016 at 15:46
  • @Jes hmm... don't know why that wouldn't work - sorry Aug 12, 2016 at 1:08

This will echo all of the items in your initial string, ensure that there is no space next to the = in text=, and use double quotes around the string. Also you're using unnecessary ;s throughout your code.



IFS=',' read -ra ids <<< "$text"

for i in "${ids[@]}"
echo "$i"

This will output

  • how to wrap the string with double quotes in code.
    – Jes
    Aug 11, 2016 at 15:04
  • Just type them.
    – Arronical
    Aug 11, 2016 at 15:10
  • No .. the string is not manually created, its from another PHP script that i am passing to bash .
    – Jes
    Aug 11, 2016 at 15:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .