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)
我已经尝试过以下
echo ${a$i}
echo $((ai))
echo ${a}${i}
c=$(echo a$i)
但没有人给出正确答案。
那((i=1;i<=3;i=i+1))
是 ksh93 语法(现在也由bash
and支持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)
归档时间: |
|
查看次数: |
880 次 |
最近记录: |