简体   繁体   English

如何在bash脚本中循环?

[英]How to loop in bash script?

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 ..)?

with bash, no need to use external commands like seq to 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

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 | 请注意,由于| ,最后一个不会将$ i的值保留在循环之外 that starts a sub-shell 这会启动一个子shell

for a in `seq 10 15`; do mkdir max${a}; done

seq will generate numbers from 10 to 15 . seq将生成1015数字。

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. 但是,当我观察到其他答案时, {START..STOP}确实更好。 Now I have to get used to create directories this much nicer way: mkdir max{10..15} . 现在我必须习惯于以更好的方式创建目录: mkdir max{10..15}

使用for循环

for i in {1..15} ; do
    mkdir max$i
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM