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:
Then you can just use the array form of the bash
read
command:where the
${text%;}
substitution removes the trailing semicolon. Note that, this way, the IFS is not modified outside of theread
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.
Alternatively, you can loop over array members directly using a
for ... in
loop: