[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Local declaration with nameref
From: |
Greg Wooledge |
Subject: |
Re: Local declaration with nameref |
Date: |
Tue, 2 May 2023 18:47:27 -0400 |
On Tue, May 02, 2023 at 10:36:31PM +0000, uzibalqa wrote:
> marin () {
> local -n _signal="$1" _modes="$2"
> [[ :"$_modes": != *:"$_signal":* ]] && _signal='SUBSCRIPT'
> }
>
> modes="ITERATE:COUNTER"
> signal="foo"
> marin signal modes
> echo "$signal"
You've made both "_signal" and "_modes" name refs. But only one of them
is actually being *used* as a name ref. The other one is just passing in
an ordinary string value.
Here's what I think you want:
marin() {
local -n _marin_signal="$1"
local _marin_modes="$2"
[[ :"$_marin_modes": != *:"$_marin_signal":* ]] && _marin_signal=SUBSCRIPT
}
Running it locally:
unicorn:~$ signal=foo
unicorn:~$ marin signal ITERATE:COUNTER
unicorn:~$ declare -p signal
declare -- signal="SUBSCRIPT"
Note the difference between the first argument, which is a variable name,
and the second argument, which is not.
Now, using the second argument as a name ref the way you were doing isn't
technically *wrong*. But I tend to avoid passing variables by reference
when it's not actually needed, especially in a language like bash where
the "pass by reference" feature is a half-baked hack that barely works.
It's also worth noting in a comment that your function is using the
first variable for both input and output. That's the kind of thing that
the caller of your function would want to know.