Ubuntu – How to convert a string into an array in bash script

bashcommand linescripts

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.

Best Answer

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
Related Question