I recently discovered a quirk in BASH that a function has direct access to variables declared in functions above in the call stack. I just started thinking about how to use this function (it promises both advantages and dangers), but one obvious application is the solution to the spirit of this problem.
I would also prefer to get the return value, rather than using a global variable when delegating the creation of an array. There are several reasons for my preferences, among which one should avoid a possible violation of the existing value and avoid leaving a value that may be invalid upon subsequent access. Although there are workarounds for these problems, the simplest is that the variable goes out of scope when the code exits with it.
My solution ensures that the array is available as needed and discarded when the function returns, and leaves the global variable of the same name unchanged.
#!/bin/bash myarr=(global array elements) get_an_array() { myarr=( $( date +"%Y %m %d" ) ) } request_array() { declare -a myarr get_an_array "myarr" echo "New contents of local variable myarr:" printf "%s\n" "${myarr[@]}" } echo "Original contents of global variable myarr:" printf "%s\n" "${myarr[@]}" echo request_array echo echo "Confirm the global myarr was not touched:" printf "%s\n" "${myarr[@]}"
Here is the output of this code: 
When the request_array function calls get_an_array, get_an_array can directly set the myarr variable, which is local to request_array. Since myarr is created with declare , it is local request_array and thus goes out of scope when request_array is returned.
Although this solution does not literally return a value, I suggest that it be taken as a whole, it satisfies the promise of a true return value of the function.
chuckj May 04 '18 at 15:41 2018-05-04 15:41
source share