0

I've below string in my shell script:

myString="app.mykey.value1,app.mykey.value2,app.mykey.value3,app.mykey.value4"

After splitting the comma separated value, I want to store each value in a different variable. For example:

var1=app.mykey.value1
var2=app.mykey.value2
var3=app.mykey.value3
var4=app.mykey.value4

How can i achieve this in shell script?

mark
  • 219
  • 1
  • 8
  • 19
  • well, short answer is, no, you can't. because you cannot generate variable names in runtime without resorting to `eval`, which you don't want to use. however, you can indeed make it to an array. is that ok to you? – Jason Hu Feb 23 '18 at 00:34
  • `IFS=, read -r -a myArray <<<"$myString"` will make `${myArray[0]}` be `app.mykey.value1`, `${myArray[1]}` be `app.mykey.value2`, etc -- which is the Right Thing here. – Charles Duffy Feb 23 '18 at 00:49
  • ...that said, there *are* ways to do indirect assignment less evil than `eval`, and we *do* have Q&A entries describing them here on the site. See [Dynamic variable names in bash](https://stackoverflow.com/questions/16553089/dynamic-variable-names-in-bash) – Charles Duffy Feb 23 '18 at 00:51

1 Answers1

0

To generate var1, var2, etc safely, use declare:

readarray -td, vals <<<"$myString"
i=1
for val in "${vals[@]}"
do
    declare "var$((i++))=$val"
done

For most purposes, though, you are better off using the array vals directly rather than creating the shell variables var1, ....

John1024
  • 109,961
  • 14
  • 137
  • 171