Ronnie Ronnie - 6 months ago 10
Bash Question

Shell Script split concatenate and re-use

In Shell script I want to achieve something like below:

str="india,uk,us,uae"


I want to split it and concatenate each item as below and assign to some variable

newstr = '-myParam="india" -myParam="uk" -myParam="us" -myParam="uae"'


so that I can use above concatenated string in my next command as below

curl "admin/admin" "localhost" $newstr.


I found a way using local IFS and for loop but the variable updated inside loop is not retaining value outside of loop because it runs in a separate bash.

Answer

Read the params into an array:

IFS=, read -a params <<< "$str"

And then loop through them and store the command in an array:

for i in "${params[@]}"; do
   command+=(-myparam=\"$i\")
done

Now you can expand it using printf "${command[@]}":

$ printf "%s " "${command[@]}"
-myparam="india" -myparam="uk" -myparam="us" -myparam="uae"

That is, now you have to say:

curl "admin/admin" "localhost" "${command[@]}"

This is based on this answer by chepner: command line arguments fed from an array.

Comments