bash 如何在bash中使用变量名生成for循环编号序列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16497501/
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
How to generate for loop number sequence by using variable names in bash?
提问by wiswit
Could anybody explain how can I use variable names in bash for loop to generate a sequence of numbers?
有人能解释一下如何在 bash for 循环中使用变量名来生成数字序列吗?
for year in {1990..1997}
do
echo ${year}
done
Results:
结果:
1990 1991 1992 1993 1994 1995 1996 1997
1990 1991 1992 1993 1994 1995 1996 1997
However
然而
year_start=1990
year_end=1997
for year in {${year_start}..${year_end}}
do
echo ${year}
done
Results:
结果:
{1990..1997}
{1990..1997}
How can I make the second case work? otherwise I have to write tedious while loops. Thanks very much.
我怎样才能使第二个案例起作用?否则我必须编写乏味的 while 循环。非常感谢。
回答by Bill
You can use something like this
你可以使用这样的东西
for (( year = ${year_start}; year <=${year_end}; year++ ))
do
echo ${year}
done
seqcommand is outdated and best avoided.
seq命令已过时,最好避免。
http://www.cyberciti.biz/faq/bash-for-loop/
http://www.cyberciti.biz/faq/bash-for-loop/
And if you want real bad to use the following syntax,
如果你真的不想使用以下语法,
for year in {${year_start}..${year_end}}
please modify it as follows:
请修改如下:
for year in $(eval echo "{$year_start..$year_end}")
http://www.cyberciti.biz/faq/unix-linux-iterate-over-a-variable-range-of-numbers-in-bash/
http://www.cyberciti.biz/faq/unix-linux-iterate-over-a-variable-range-of-numbers-in-bash/
Personally, I prefer using for (( year = ${year_start}; year <=${year_end}; year++ )).
就个人而言,我更喜欢使用for (( year = ${year_start}; year <=${year_end}; year++ )).
回答by Sithsu
Try following:
尝试以下操作:
start=1990; end=1997; for year in $(seq $start $end); do echo $year; done

