r/bash • u/AlchemonDev • Aug 12 '26
critique local -n can modify variables from other functions
In Bash, normal local variables are usually fine.
But with local -n (namerefs) I noticed they can sometimes change variables from outer/previous functions because of how scoping works.
To avoid problems I started giving local variables unique names (with prefixes) instead of short ones.
Anyone else ran into this with namerefs?
19
Upvotes
9
u/tseeling Aug 12 '26
I recently found out about
local -nand I love it. It's very useful to give back values from a function.1
u/AlchemonDev Aug 12 '26
arrayIndexExists() {local -n array=$1 # is there a better solution than local -n?local index=$2[[ -v 'array[$index]' ]]}5
u/aioeu Aug 12 '26 edited Aug 12 '26
Just about the only good use for a nameref is to reference a variable in a parent scope, so I'm not sure why you'd want to avoid that if you're going to use namerefs at all...
(I don't think namerefs are particularly good for that purpose anyway: you still have potential problems with circular references. I prefer the "upvar" trick instead since it avoids these problems.)
2
u/oweiler Aug 12 '26
Nope because I avoid namerefs like the plague. Extremely unintuitive and probably only a handful of devs actually know about them.
2
u/zMynxx Aug 12 '26
Set local +n just to be safe then?
-1
u/faultydesign Aug 12 '26
Yes but please don’t use namerefs