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

2 Answers

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy