Passing a array to a function, a basic feature in modern language, seems to be only possible in KSH. Not in BASH. Depite all my efforts I couldn't come to a solution. See the following examples:
Which is rather inelegant and clumsy. All I wanted is to create a *local* copy of the array whose name is passed to the function as positional parameter ($1 $2 ....). By the way, how can I copy an array without looping throught it and assigning values one by one. Of course, the following doesn't work:
OK, here is what works in bash. Remember, the question was to pass an array to a function and make sure that whatever is done by the function remains local. If the local scope isn't necessary, just remove the "local" declaration.
#!/bin/bash
function print_array {
# Setting the shell's Internal Field Separator to null
OLD_IFS=$IFS
IFS=''
# Create a string containing "colors[*]"
local array_string="$1[*]"
# assign loc_array value to ${colors[*]} using indirect variable reference
local loc_array=(${!array_string})
# Resetting IFS to default
IFS=$OLD_IFS
# Checking the second element "Light Gray" (the one with a space)
echo ${loc_array[1]}
}
# create an array and display contents
colors=('Pink' 'Light Gray' 'Green')
echo ${colors[*]}
# call function with positional parameter $1 set to array's name
print_array colors
# checking whether the function "local" loc_array is visible here
echo "Does the local array exist here? -->${loc_array[*]}<--"
exit 0
This returns:
Pink Light Gray Green
Light Gray
Does the local array exist here? --><--
We can also "copy" an array the same way: setting IFS to NULL permit to do variable expansion that preserves the possible spaces in array's elements.