在 bash 脚本中通过引用更新变量?

Updating variables by reference in bash script?

是否可以在 bash 脚本 in the way it is done in C++ 中通过引用使用变量?

假设我有如下脚本:

#!/bin/bash

A="say"
B=$A
echo "B is $B"
A="say it"
echo "B is $B" # This does not get the new value of A but is it possible to using some trick?

你在上面的脚本中看到 echo "B is $B 输出 B is say 即使 A 的值已从 say 更改为 say it。我知道像 B=$A 这样的重新分配会解决它。但我想知道 B 是否有可能持有对 A 的引用,以便 BA 更新后立即更新它的值。这发生在没有重新分配的情况下,即 B=$A。这可能吗?

我从 Lazy Evaluation in Bash 了解到 envsubst。是按照方法去做的吗?

A="say"
B=$A
echo "B is $B"
envsubst A="say it"
echo "B is $B"

Updating variables by reference in bash script?

并且与 C++ 类似,一旦您为变量分配 ,就无法跟踪该值的来源。在 shell 中,所有变量都存储字符串。您可以将变量名称作为字符串存储在另一个变量中,该变量充当引用。您可以使用:

Bash间接展开:

A="say"
B=A
echo "B is ${!B}"
A="say it"
echo "B is ${!B}"

Bash 名称引用:

A="say"
declare -n B=A
echo "B is $B"
A="say it"
echo "B is $B"

邪恶eval:

A="say"
B=A
eval "echo \"B is $$B\""
A="say it"
eval "echo \"B is $$B\""

Is this possible?

是 - 将变量名称存储在 B 中,而不是值。

envsubst from Lazy Evaluation in Bash. Is following the way to do it?

不,envsubst 做了一些不同的事情。