You cannot have Bash pass an array by reference, or have it copied as a single entity.
There are two approaches to achieving the desired result.
The first one is copying the data
function __test()
{
declare -a array=("a" "b" "c" "d")
my_command -c "${array[@]}"
}
my_command()
{
# Handle options
[[ "$1" != -c ]] || shift
# Get your data back in array form by collecting
# positional parameters in an array
declare -a array=("$@")
# Display element at position 2
echo "${array[2]}"
# Display all elements
echo "${array[@]}"
}
If mycommand is an external program in another language, then you would receive the data as positional parameters.
The second approach is indirection, and will only work if the data is used inside the same Bash script so that the variable can be access in the same scope.
function __test()
{
declare -a array=("a" "b" "c" "d")
my_command -c array
}
my_command()
{
# Handle options
[[ "$1" != -c ]] || shift
varname="$1"
# Access element at position 2
x="$varname[2]"
echo "${!x}"
# Access all elements
x="$varname[@]"
echo "${!x}"
}
You need to make sure the variable name used does not contain any unwanted data, or else there could be risks or code injection, so unless the variable name is fully under the control of your program (no chance of user input being included in the variable name), you have to find a way to sanitize it.
Recent variables of bash have a -n option in variable declaration statements (such as local) which you may also want to take a look at, but I would think this is not deployed widely enough to be used except for known configurations.
Please note that I would normally declare all variables local in functions unless I have a specific reason for not doing so, this has been omitted in the code above for clarity purposes.
(a b c d)is an array value, when no such value exists.bashonly has array variables, which provide syntax for addressing individual string values using the same variable name.