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?

2 Answers 2

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[@]}")
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Yup, that is it. Just wrap the argument list in parens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.