Debian Bash 关联数组自(内部)引用

njc*_*njc 3 debian bash array

我正在尝试使用 Debian Gnu-Linux 12.4、22.12.3 和 Bash 5.2.15 构建一个关联数组,其中数组中的键值对引用同一数组中的其他键值对。

例子,

declare -A test=(
    [0]=0
    [1]=1
    [2]=2
    [3]=$((test[1]+test[2]))
    [4]="${test[1]} ${test[2]}"
)
Run Code Online (Sandbox Code Playgroud)

当我在 Konsole 中执行以下 echo 语句时,

echo "${test[1]}"
echo "${test[2]}"
echo "${test[3]}"
echo "${test[4]}"
Run Code Online (Sandbox Code Playgroud)

我有时会得到这样的结果,

1
2
0

Run Code Online (Sandbox Code Playgroud)

有时我得到了我想要的

1
2
3
1 2
Run Code Online (Sandbox Code Playgroud)

由于这种不一致(这可能完全是我的行为造成的),我有几个问题。

  1. 这可以做到吗?
  2. 如果是,有正确的方法吗?

另外,我找不到一致的方法来复制这两个不同的结果,无论发生什么或如何发生。

use*_*686 7

不是您想要做的方式,因为变量引用不存储在数组 \xe2\x80\x93 中,而是立即被评估为“字符串文字”表达式 \xe2\x80\x93 的一部分,因此评估引用时,对 的分配test尚未完成。(与许多其他编程语言相同!)

\n

(尽管语法相似,但只有test=\xe2\x80\xa6ortest[3]=\xe2\x80\xa6是实际的变量赋值,但( [0]=\xe2\x80\xa6 )不是 \xe2\x80\x93 Bash 的数组键/值语法只是模仿真正的test[3]=\xe2\x80\xa6赋值语法,但在其他语言中,通常看起来完全相同的概念类似test = { "0": 1234 }或类似。)

\n

您将需要多次作业才能正确完成:

\n
declare -A test=(\n    [0]=0\n    [1]=1\n    [2]=2\n)\n\ntest[3]=$(( test[1] + test[2] ))\n\ntest[4]="${test[1]} ${test[2]}"\n\ntest+=(\n    [5]="${test[3]} and ${test[4]}"\n    [6]="${test[4]} but not yet ${test[5]}"\n)\n
Run Code Online (Sandbox Code Playgroud)\n

上例中的四个操作中的每一个都是一个单独的赋值;首先处理所有变量引用和其他扩展,然后更新 的$值。test

\n
\n

另外,我找不到一致的方法来复制这两个不同的结果,无论发生什么或如何发生。

\n
\n

如果您从示例中的扩展中得到结果,则它正在使用先前分配的值。在赋值之前(和之后)放置一个declare -p test以查看存储了哪些值。

\n

为了确保实验的一致性,请unset test在每次尝试之前执行此操作。

\n