About the "nameref" feature in bash...
Sujet : About the "nameref" feature in bash...
De : gazelle (at) *nospam* shell.xmission.com (Kenny McCormack)
Groupes : comp.unix.shellDate : 08. Dec 2024, 13:51:05
Autres entêtes
Organisation : The official candy of the new Millennium
Message-ID : <vj44np$1eiqc$1@news.xmission.com>
User-Agent : trn 4.0-test77 (Sep 1, 2010)
Bash has a "nameref" attribute on variables, that basically makes them like
"pointers" in languages like C. That is, the nameref variable has a value,
which is the name of another variable, and any/all references to the
nameref are, in fact, references to the other variable (with 2 exceptions
as discussed below). So, it works like this:
# Create a nameref variable and give it the value "foo"
declare -n MyNameRef=foo
foo=bar
echo $MyNameRef
(prints bar)
MyNameRef="Not bar"
echo $foo
(prints Not bar)
Now, the docs present this feature as being primarily useful with
functions. That is, something like:
foo() {
local -n MyNameRef=$1
# Function manipulates MyNameRef, but is, in fact, manipulating
# the variable whose name was passed as an arg to the function.
}
So, if we call foo as: foo bar
then references to MyNameRef inside foo() are, in fact, references to the
global variable "bar".
This is all well and good, but it leaves open the question of "How do I
assign a value to the nameref itself, given that any reference to the
nameref gets converted to a reference to whatever the nameref points to?"
The answer, as far as I can tell, is that there are exactly 2 exceptions to
the "always dereference" rule (for setting the value):
1) Use "declare" (or one of its synonyms, e.g., "local") to do the
assignment. This works, but is somewhat unappealing, since you may
end up declaring a variable more than once (which seems intuitively
wrong).
2) Use a "for" loop, like this:
for MyNameRef in one two three; do echo $MyNameRef; done
This magically assigns MyNameRef the values one, two, and three and
displays the values of those variables. Note that is different in
effect from the seemingly equivalent:
MyNameRef=one; echo $MyNameRef
MyNameRef=two; echo $MyNameRef
MyNameRef=three; echo $MyNameRef
Note: There is a syntax for reading the value of the nameref, but this
cannot be used to set the value. The syntax is: echo ${!MyNameRef}
In conclusion, my "reason for posting" is to confirm that I've got it right
that there are only 2 ways to set the value. Am I missing anything?
--
"We are in the beginning of a mass extinction, and all you can talk
about is money and fairy tales of eternal economic growth."
- Greta Thunberg -
Haut de la page
Les messages affichés proviennent d'usenet.
NewsPortal