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+.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate