bash 如何在bash脚本中循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4007667/
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 loop in bash script?
提问by co-worker
i have following lines in a bash script under Linux:
我在 Linux 下的 bash 脚本中有以下几行:
...
mkdir max15
mkdir max14
mkdir max13
mkdir max12
mkdir max11
mkdir max10
...
how is the syntax for putting them in a loop, so that i don't have to write the numbers (15,14..) ?
将它们放入循环中的语法如何,以便我不必写数字 (15,14..) ?
回答by ghostdog74
with bash, no need to use external commands like seqto generate numbers.
使用 bash,无需使用诸如seq生成数字之类的外部命令。
for i in {15..10}
do
mkdir "max${i}"
done
or simply
或者干脆
mkdir max{01..15} #from 1 to 15
mkdir max{10..15} #from 10 to 15
say if your numbers are generated dynamically, you can use C style for loop
说如果你的数字是动态生成的,你可以使用 C 风格的循环
start=10
end=15
for((i=$start;i<=$end;i++))
do
mkdir "max${i}"
done
回答by Chen Levy
No loop needed for this task:
此任务不需要循环:
mkdir max{15..10} max0{9..0}
... but if you need a loop construct, you can use one of:
...但如果你需要一个循环结构,你可以使用以下之一:
for i in $(seq [ <start> [ <step> ]] <stop>) ; do
# you can use $i here
done
or
或者
for i in {<start>..<stop>} ; do
# you can use $i here
done
or
或者
for (( i=<start> ; i < stop ; i++ )) ; do
# you can use $i here
done
or
或者
seq [ <start> [ <step> ]] <stop> | while read $i ; do
# you can use $i here
done
Note that this last one will not keep the value of $i outside of the loop, due to the |that starts a sub-shell
请注意,最后一个不会将 $i 的值保留在循环之外,因为|它启动了一个子 shell
回答by eumiro
for a in `seq 10 15`; do mkdir max${a}; done
seqwill generate numbers from 10to 15.
seq将生成从10到 的数字15。
EDIT:I was used to this structure since many years. However, when I observed the other answers, it is true, that the {START..STOP}is much better. Now I have to get used to create directories this much nicer way: mkdir max{10..15}.
编辑:多年来我已经习惯了这种结构。但是,当我观察其他答案时,确实如此,后者{START..STOP}要好得多。现在我必须习惯以这种更好的方式创建目录:mkdir max{10..15}.
回答by chrisaycock
for i in {1..15} ; do
mkdir max$i
done

