我有这个:
test1="1"
test2="2"
test3="3"
for i in "$test1" "$test2" "$test3"; do
echo "$i"
done ;
Run Code Online (Sandbox Code Playgroud)
我想回显$i变量名,而不是其内容。
回声输出应为“test1”、“test2”或“test3”
我怎样才能做到这一点?
Luc*_*ini 15
如果你真的想这样做,就这样做:
#!/bin/bash
test1='1'
test2='2'
test3='3'
for v in "test1" "test2" "test3"; do
echo "The variable's name is $v"
echo "The variable's content is ${!v}"
done
Run Code Online (Sandbox Code Playgroud)
但是您可能更喜欢使用数组而不是动态变量名,因为这可能被视为一种不好的做法,并使您的代码更难理解。所以考虑这个,更好,形式:
#!/bin/bash
test[0]='1'
test[1]='2'
test[2]='3'
for ((i=0;i<=2;i++)); do
echo "The variable's name is \$test[$i]"
echo "The variable's content is ${test[$i]}"
done
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20339 次 |
| 最近记录: |