Reputation: 409
I am trying to initialize an array with multiple variables as below .
StringOne="This is a Test String"
StringTwo="This is a New String"
read -r -a Values <<< "$StringOne" "$StringTwo"
But It seems like array is getting values from only the first variable .ie StringOne
$ echo ${Values[0]}
This
$ echo ${Values[1]}
is
$ echo ${Values[2]}
a
$ echo ${Values[3]}
Test
${Values[4]}
String
$ echo ${Values[5]}
$ echo ${Values[6]}
$
What is wrong with this way of passing variable value for array initialization ? Cant we pass multiple variables with <<< operator ?
Upvotes: 1
Views: 785
Reputation:
Use:
read -r -a Values <<< "$StringOne"" ""$StringTwo"
Or:
read -r -a Values <<< "$StringOne"' '"$StringTwo"
Or:
out="$StringOne $StringTwo"
read -r -a Values <<< "$out"
Or some other variation on this theme.
This works because the string sent via <<<
is the result of the expansion of what in on the right of it. We can make both variables act as one long string by concatenating them.
Upvotes: 0
Reputation: 180286
What is wrong with this way of passing variable value for array initialization ? Cant we pass multiple variables with <<< operator ?
Yes and no. The <<<
operator takes one shell word as its operand, as is presented pretty clearly in its documentation. But you can combine the values of multiple variables in a single shell word by appropriate use of quoting:
StringOne="This is a Test String"
StringTwo="This is a New String"
read -r -a Values <<< "$StringOne $StringTwo"
echo "${Values[@]}"
Output:
This is a Test String This is a New String
Upvotes: 2