英文:
Link variables in GNU Bash (4.4.20)
问题
在GNU Bash(版本5.0.17)中,我想要链接两个(或更多)变量,即当变量#1的值发生变化时,变量#2应自动设置为变量#1的值,反之亦然。
我尝试了以下方法(都是在Bash命令行中),它可以工作,但只有在在变量名后插入一个空格时才有效。然而,这对我来说不够好,我更希望myvar1=test
,即没有空格,但我担心这可能不可能...?
$ bash --version
> GNU bash, version 5.0.17(1)-release
$ myvar1() {
myvar1=$(echo "$@" | cut -d'=' -f2-)
myvar2="$myvar1"
}
$ myvar2() {
myvar1=$(echo "$@" | cut -d'=' -f2-)
myvar2="$myvar1"
}
$ echo "$myvar1:$myvar2:" # 此时未设置
> ::
$ myvar1=abc
$ echo "$myvar1:$myvar2:"
> abc:abc:
$ myvar2=def
$ echo "$myvar1:$myvar2:"
> def:def:
这样做的原因是为了保持旧变量仍然在使用,同时支持在其他地方使用的新变量,这些变量对值应该保持一致。
英文:
In GNU Bash (5.0.17) I would like to link two (or more) variables i.e., when variable #1 changes value, variable #2 should automatically have its value set to the value of variable #1 and vice versa.
I've tried the following (all from Bash command line), and it works, but only when you insert a space after the variable name during assignment.
However this not good enough for me, I'd prefer myvar1=test
i.e. without space, but I fear this is not possible...?
$ bash --version
> GNU bash, version 5.0.17(1)-release
$ myvar1() {
myvar1=$(echo "$@" | cut -d'=' -f2-)
myvar2="$myvar1"
}
$ myvar2() {
myvar1=$(echo "$@" | cut -d'=' -f2-)
myvar2="$myvar1"
}
$ echo "$myvar1:$myvar2:" # Unset at this point
> ::
$ myvar1 =abc
$ echo "$myvar1:$myvar2:"
> abc:abc:
$ myvar2 =def
$ echo "$myvar1:$myvar2:"
> def:def:
The reason for this is to keep legacy variables still being used but also support new variables, used elsewhere, where these variable pairs should go hand in hand value-wise.
答案1
得分: 3
根据您的要求,以下是翻译好的部分:
"As your bash is recent enough you could simply make VAR2
a nameref of VAR1
:"
(由于您的Bash版本足够新,您可以简单地将 VAR2
设为 VAR1
的 nameref:)
"Note that the association is symmetrical:"
(请注意,关联是对称的:)
"(but they are not equivalent, VAR2
is a nameref, VAR1
is not; for instance, to unset VAR1
you just unset VAR1
, while to really unset VAR2
you need the -n
option of unset
, else, with unset VAR2
, you unset VAR1
)."
(但它们并不等同,VAR2
是一个 nameref,VAR1
不是;例如,要取消设置 VAR1
,您只需执行 unset VAR1
,而要真正取消设置 VAR2
,您需要使用 unset
命令的 -n
选项,否则,使用 unset VAR2
会取消设置 VAR1
。)
英文:
As your bash is recent enough you could simply make VAR2
a nameref of VAR1
:
$ declare -n VAR2=VAR1
$ VAR1=foo
$ echo $VAR2
foo
Note that the association is symmetrical:
$ VAR2=bar
$ echo $VAR1
bar
(but they are not equivalent, VAR2
is a nameref, VAR1
is not; for instance, to unset VAR1
you just unset VAR1
, while to really unset VAR2
you need the -n
option of unset
, else, with unset VAR2
, you unset VAR1
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论