3

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';
OIFS=$IFS;
IFS=',';
ids=$($text);
for (i=0; i<${#ids[@]}; ++i);
do
echo "$i"
done
IFS=$OIFS

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

1
  • 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

7

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

text="'xdc','cde','erd','ded','ded','kie';"

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
4
  • 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
1

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.

#!/bin/bash

text="'xdc','cde','erd','ded','ded','kie'"

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

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

This will output

'xdc'
'cde'
'erd'
'ded'
'ded'
'kie'
3
  • 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 .