我想回显 a1、a2、a3 中的值。但是我的代码只打印 a1、a2 和 a3 而不是存储在它们里面的值

Vis*_*ury 2 shell variable-substitution variable

a1="one"
a2="two"
a3="three"
for ((i=1;i<=3;i=i+1)); do
     echo $a$i
done 
Run Code Online (Sandbox Code Playgroud)

我已经尝试过以下

  1. echo ${a$i}
  2. echo $((ai))
  3. echo ${a}${i}
  4. c=$(echo a$i)

但没有人给出正确答案。

Sté*_*las 5

((i=1;i<=3;i=i+1))是 ksh93 语法(现在也由bashand支持zsh(尽管在for((in之间需要空格zsh))。

在(4.3、2014 或更高ksh93版本)的最新版本中bash,您可以执行以下操作:

a1="one"
a2="two"
a3="three"
for ((i=1;i<=3;i=i+1));do
    typeset -n name="a$i"
    printf '%s\n' "$name"
done 
Run Code Online (Sandbox Code Playgroud)

在 中zsh,您可以使用变量间接语法:(${(e)code}自 1996 年 5 月起),${(P)name}(自 1999 年起)

a1="one"
a2="two"
a3="three"
for ((i=1;i<=3;i=i+1));do
    name=a$i
    printf '%s\n' "${(P)name}"
    # or
    code="\$a$i"
    printf '%s\n' "${(e)code}"
    # or combined:
    printf '%s\n' "${(e):-\$a$i}" "${(P)${:-a$i}}"
done 
Run Code Online (Sandbox Code Playgroud)

bash 还添加了自己的变量间接功能,但使用了不同的语法(在 1996 年 12 月的 2.0 中),其含义几乎与 ksh93 的语法相反:

a1="one"
a2="two"
a3="three"
for ((i=1;i<=3;i=i+1));do
    name=a$i
    printf '%s\n' "${!name}"
done 
Run Code Online (Sandbox Code Playgroud)

使用任何 POSIX shell(包括但不限于 ksh93、bash 或 zsh),您始终可以执行以下操作:

a1="one"
a2="two"
a3="three"
i=1; while [ "$i" -le 3 ]; do
    name=a$i
    eval "value=\${$name}"
    printf '%s\n' "$value"
    i=$((i + 1))
done 
Run Code Online (Sandbox Code Playgroud)