On Tue, Aug 24, 2021 at 04:16:46PM +0200, Léa Gris wrote: > string2array() { > # Splits the string's characters into the array > # $1: The input string > # $2: The output array name > [[ "$1" =~ ${1//?/(.)} ]] > # shellcheck disable=SC2178 # shellcheck broken nameref type check > local -n arr="$2" > # shellcheck disable=SC2034 # shellcheck broken nameref usage check > arr=("${BASH_REMATCH[@]:1}") > }
Be careful with namerefs used to pass variables by reference. They're evaluated using the same dynamic scope rules as any other local variable. If the caller of your function uses "arr" as the second argument, they'll get an error. The only strategy I've found to deal with this is to choose ugly local variable names in any function that uses this approach. E.g. instead of "arr", you might call your variable "_string2array_arr". Anything that the caller is unlikely to use, or which you reserve for this purpose as part of some documented API for your functions, should work.