Interview Prep/Shell Scripting/Variables, quoting and expansions

What is a nameref (`declare -n`) and what problem does it solve?

AdvancedConceptVariables, quoting and expansions
Answer

A nameref is an alias to another variable, which lets a function write into a variable (or array) whose name the caller passes, without eval.

split_csv() {            # split_csv OUT_ARRAY "a,b,c"
  local -n _out=$1
  IFS=, read -r -a _out <<<"$2"
}
split_csv hosts "web1,web2,web3"
echo "${#hosts[@]} ${hosts[1]}"   # 3 web2

Prefix nameref locals with _ so they do not collide with the caller's variable name (local -n hosts=$1 with a caller variable hosts is a circular reference). Requires Bash 4.3+.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions