brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: local -n lets a bash function change an array you pass by name

Bash
~/tips/tip-bash-declare-n-nameref

local -n _list=$1

Passes an array to a bash function by name, so the function can change the original.

Passing an array to a bash function has always been awkward. You either spread it out as arguments and lose the structure, or you fall back on eval. Since bash 4.3 there’s a cleaner way: a name reference.

A variable with the nameref attribute (declare -n or local -n) points at another variable. Everything you do with it happens to the variable it points at. So you pass the name of the array, and the function works on the original:

add_app() {
  local -n _list=$1
  _list+=("$2")
}

apps=(jellyfin)
add_app apps sonarr
add_app apps radarr
declare -p apps
# declare -a apps=([0]="jellyfin" [1]="sonarr" [2]="radarr")

It also works the other way, as a way to return more than one value. Give the function the name of the variable it should fill, and it writes the result there instead of printing it and making you capture it with $( ). That also keeps the function in the current shell, so it can set other variables too.

The caveat is the name of the reference. If the caller happens to pass a variable with the same name as your nameref, say local -n apps=$1 called with apps, bash prints a “circular name reference” warning and the function doesn’t touch the caller’s array. That’s why I’d give the reference an unusual name, like _list above. And it needs bash 4.3 or newer, so older systems will choke on the -n option.

Further reading: bash(1) manual page, Bash NEWS (new features per version)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link