bash shell脚本中的指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16678381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pointer in shell script?
提问by gforce89
I am trying to print a filename which contains decimal point numbers... say
我正在尝试打印一个包含小数点数字的文件名......说
L2.3stop.txt
I have variables defined as :
我有变量定义为:
z1=2.3
z2=3.4
z3=7.8
z4=8.9
and so on
等等
In a for loop i runs from 1 to 5
在 for 循环中,我从 1 到 5
Inside the loop if I do
如果我这样做,则在循环内
temp=`echo z$i`
and then I print the file name using
然后我使用打印文件名
echo L${temp}stop.txt
it just prints
它只是打印
Lz1stop.txt
Lz2stop.txt
etc..
等等..
How can I print the desired filename....
如何打印所需的文件名....
I also tried using
我也尝试使用
echo L$((z$i))stop.txt
but this only works when z1, z2, z3 etc are integers and not floating numbers....
但这仅在 z1、z2、z3 等是整数而不是浮点数时才有效....
回答by Kent
I hope this helps:
我希望这有帮助:
z1=2.3
z2=3.4
z3=7.8
z4=8.9
for i in {1..4};do
echo L$(eval "echo $z"$i)stop.txt
done
or this should work too:
或者这也应该有效:
for i in {1..4};do
echo L$(echo $(echo "$z$i"))stop.txt
done
outputs:
输出:
L2.3stop.txt
L3.4stop.txt
L7.8stop.txt
L8.9stop.txt
回答by William Pursell
This is not portable, but in bash you can do:
这不是便携式的,但在 bash 中你可以这样做:
name=z$i
echo ${!name}
回答by Jonathan Leffler
Best (using an array):
最佳(使用数组):
z=( 2.3 3.4 7.8 8.9 9.8 ) # Added fifth value
for x in "${z[@]}"
do
echo L${x}stop.txt
done
Less good (using indirect expansion— a bashfeature):
不太好(使用间接扩展——一个bash特性):
z1=2.3
z2=3.4
z3=7.8
z4=8.9
z5=9.8 # Added fifth value
for i in {1..5}
do
v=z$i
echo L${!v}stop.txt
done
Both produce:
两者都产生:
L2.3stop.txt
L3.4stop.txt
L7.8stop.txt
L8.9stop.txt
L9.8stop.txt
Both avoid using evalwhich is not too harmful in this context but is dangerous (and difficult to use correctly) in general.
两者都避免使用eval在这种情况下不太有害但通常是危险的(并且难以正确使用)。
回答by Hyman qi
If you have defined variable z, you can do this:
如果你定义了变量z,你可以这样做:
for v in ${!z*}; do echo L${!v}stop.txt; done
or:
或者:
for v in z{1..4}; do echo L${!v}stop.txt; done

