Insert variable value as element in array

9,449

The array assignment is correct, you should check the printing part.

variable="Hello there"
array[0]=$variable
echo "${array[0]}"

output

Hello there
Share:
9,449

Related videos on Youtube

thatguy2000
Author by

thatguy2000

Updated on September 18, 2022

Comments

  • thatguy2000
    thatguy2000 over 1 year

    If I have a variable that has a value stored and I want to place that value into an array using the name of the variable, how would I do this?

    e.g.:

    variable="Hello there"
    array[0]=$variable
    

    does not make array[0] equal to "Hello there"

    What am I doing wrong?

    • Stéphane Chazelas
      Stéphane Chazelas over 9 years
      Possibly you invoked the split+glob operator with cmd ${array[0]} or cmd ${array[@]}. That should be cmd "${array[0]}" or cmd "${array[@]}", like printf '<%s>\n' "${array[@]}"