terr
terr

Reputation: 51

how to reset a nameref in bash

Let's say I have something like this with bash

func ()
{
   local -n ref
   ...
   ref="somevar"
   ref="somevalue"
   ...
   ref="someothervar"
}

So, ref is a nameref bash style. With the first assignment to it the var (somevar) to be modified through ref is set. With the second assignment to ref the var somevar is modified. Then let's say that I wanted to use ref to modify another var someothervar. Obviously doing just what you see in the third assignment to ref does not work, since bash thinks we are still modifying somevar through ref and so the string someothervar is assigned to somevar.

The only way I found to "reset" the var referenced by ref is by doing this

func ()
{
   local -n ref
   ...
   ref="somevar"
   ref="somevalue"
   ...
   unset -n ref
   local -n ref
   ref="someothervar"
}

That is, by first unsetting ref with unset -n (notice the -n) and then re-declaring it.

I think there should be a less cumbersome way of doing this, ideally with a specific syntax variation for an assignment to ref meant to reset its referred variable. But I wasn't able to find anything.

Any ideas?

Thanks

Upvotes: 0

Views: 168

Answers (0)

Related Questions