我正在寻找基本的循环:
for(int i = 0; i < MAX; i++) { doSomething(i); }
但对于bash.
从这个网站:
for i in $(seq 1 10); do echo $i done
for ((i = 0 ; i < max ; i++ )); do echo "$i"; done
bash for
包含一个变量(迭代器)和迭代器将迭代的单词列表.
因此,如果您有一个有限的单词列表,只需将它们放在以下语法中:
for w in word1 word2 word3 do doSomething($w) done
您可能希望迭代某些数字,因此您可以使用该seq
命令为您生成数字列表:(例如,从1到100)
seq 1 100
并在FOR循环中使用它:
for n in $(seq 1 100) do doSomething($n) done
请注意$(...)
语法.这是一个bash行为,它允许你将输出从一个命令(在我们的例子中seq
)传递给另一个命令(the for
)
当您必须遍历某个路径中的所有目录时,这非常有用,例如:
for d in $(find $somepath -type d) do doSomething($d) done
生成列表的可能性是无限的.
Bash 3.0+可以使用以下语法:
for i in {1..10} ; do ... ; done
..避免产生外部程序来扩展序列(例如seq 1 10
).
当然,这与for(())
解决方案存在同样的问题,与bash甚至特定版本相关(如果这对您很重要).
尝试bash
内置帮助:
$ help for for: for NAME [in WORDS ... ;] do COMMANDS; done The `for' loop executes a sequence of commands for each member in a list of items. If `in WORDS ...;' is not present, then `in "$@"' is assumed. For each element in WORDS, NAME is set to that element, and the COMMANDS are executed. for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done Equivalent to (( EXP1 )) while (( EXP2 )); do COMMANDS (( EXP3 )) done EXP1, EXP2, and EXP3 are arithmetic expressions. If any expression is omitted, it behaves as if it evaluates to 1.