0

I am trying to change the values inside an array that is a copy of arguments array ("$@"). Let's say I execute the script as follows: $ sh script.sh 1 2 3

This is the script:

list="$@"
echo ${list[*]}
list[1]=4
echo ${list[*]}

Expected output:

1 2 3
1 4 3

What I actually get:

1 2 3
1 2 3 4

Any idea what causes this behavior and how can I fix it?

Max Mikhaylov
  • 772
  • 13
  • 32

2 Answers2

1

list="$@" sets list to a plain variable, not an array. Use list=("$@") to store it as an array instead. BTW, you should generally use "${list[@]}" to get the elements of an array, instead of ${list[*]} to avoid problems with whitespace in elements, wildcards getting expanded to lists of matching files, etc.

In general, this is the proper way to copy an array:

copyarray=("${oldarray[@]}")
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
0

Just found this answer. Command line arguments array is not quite a normal array and has to be converted to an actual array first as follows:

list=("$@")
Community
  • 1
  • 1
Max Mikhaylov
  • 772
  • 13
  • 32