Using references (easiest way; best and only way for passing associative arrays):
print()
{
[ "$1" = "arr" ] || { declare -n arr; arr="$1"; }
# The name of reference mustn't match the input coming to the function.
# If it does, use the name directly as array instead of reference.
echo "${arr[@]}"
}
print arr
For normal (non-associative) arrays:
Here is a function that copies the passed array in new (local) array for usage. Can be time-taking for long arrays.
copy_fn()
{
eval local newarr=\(\${$1[@]}\)
echo ${newarr[@]}
}
Further, like in C++ you can only pass an array pointer, but in python, as a shared variable which you can modify as well.
Here is the shared variables approach.. useful for long arrays.
modify_arr()
{
eval local ptr=$1 # works as if ptr is a pointer to actual "array-name" (arr) # the original array is, thus, still same, not a copy
eval $ptr+=(1) # modify the array
echo ${ptr[@]} # will print name of the array (arr)
eval echo \$\{$ptr[@]\} # will print the actual array (arr)
}
modify_arr a
echo ${a[@]}
-Himanshu