Reputation: 17902
Amongst the answers to How to copy an array in Bash?, the solution for copying an array from one variable to another is arrayClone=("${oldArray[@]}")
.
However, what if the array I need to copy is the list of arguments, @
?
A simple test script like:
#! /bin/bash
argsCopy=("${@[@]}")
Fails with an error:
line 3: ${@[@]}: bad substitution
Upvotes: 6
Views: 4486
Reputation: 17902
By way of experimentation, it appears that argsCopy=("$@")
is sufficient.
When I run the following via ./test.sh 1 2 3\ 4
,
#! /bin/bash
set -x
argsCopy=("$@")
echo "${argsCopy[@]}" > /dev/null
it outputs:
+ argsCopy=("$@")
+ echo 1 2 '3 4'
However, like many things in sh/bash, I can't explain what rules of the language cause this to work, or under what circumstances it might end up failing.
Upvotes: 7