Max Mikhaylov
Max Mikhaylov

Reputation: 792

Change values of array that is a copy of argument array

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?

Upvotes: 0

Views: 353

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125898

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[@]}")

Upvotes: 1

Max Mikhaylov
Max Mikhaylov

Reputation: 792

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=("$@")

Upvotes: 0

Related Questions