如何在 bash 中编写 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49110/
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 do I write a for loop in bash
提问by John Meagher
I'm looking for the basic loop like:
我正在寻找基本循环,如:
for(int i = 0; i < MAX; i++) {
doSomething(i);
}
but for bash.
但对于 bash。
回答by Nick Stinemates
for ((i = 0 ; i < max ; i++ )); do echo "$i"; done
回答by Fernando Barrocal
The bash for
consists on a variable (the iterator) and a list of words where the iterator will, well, iterate.
bashfor
包含一个变量(迭代器)和一个单词列表,迭代器将在其中迭代。
So, if you have a limited list of words, just put them in the following syntax:
因此,如果您的单词列表有限,只需将它们放入以下语法中:
for w in word1 word2 word3
do
doSomething($w)
done
Probably you want to iterate along some numbers, so you can use the seq
command to generate a list of numbers for you: (from 1 to 100 for example)
可能你想迭代一些数字,所以你可以使用seq
命令为你生成一个数字列表:(例如从 1 到 100)
seq 1 100
and use it in the FOR loop:
并在 FOR 循环中使用它:
for n in $(seq 1 100)
do
doSomething($n)
done
Note the $(...)
syntax. It's a bash behaviour, it allows you to pass the output from one command (in our case from seq
) to another (the for
)
注意$(...)
语法。这是一种 bash 行为,它允许您将一个命令的输出(在我们的例子中为 from seq
)传递到另一个(the for
)
This is really useful when you have to iterate over all directories in some path, for example:
当您必须遍历某个路径中的所有目录时,这非常有用,例如:
for d in $(find $somepath -type d)
do
doSomething($d)
done
The possibilities are infinite to generate the lists.
生成列表的可能性是无限的。
回答by David Gardner
Bash 3.0+can use this syntax:
Bash 3.0+可以使用以下语法:
for i in {1..10} ; do ... ; done
..which avoids spawning an external program to expand the sequence (such as seq 1 10
).
..这避免了生成外部程序来扩展序列(例如seq 1 10
)。
Of course, this has the same problem as the for(())
solution, being tied to bash and even a particular version (if this matters to you).
当然,这与for(())
解决方案存在相同的问题,绑定到 bash 甚至特定版本(如果这对您很重要)。
回答by Pat Notz
Try the bash
built-in help:
尝试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.
回答by nobar
#! /bin/bash
function do_something {
echo value=
}
MAX=4
for (( i=0; i<MAX; i++ )) ; {
do_something ${i}
}
Here's an example that can also work in older shells, while still being efficient for large counts:
这是一个也可以在较旧的 shell 中工作的示例,同时对于大量计数仍然有效:
Z=$(date) awk 'BEGIN { for ( i=0; i<4; i++ ) { print i,"hello",ENVIRON["Z"]; } }'
But good luck doing useful things inside of awk
: How do I use shell variables in an awk script?
但是祝你好运在里面做有用的事情awk
:如何在 awk 脚本中使用 shell 变量?
回答by terson
I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of bash's brace expansion to create for loops that allow me to create non-numerical for-loops.
我通常喜欢在标准 for 循环上使用一个轻微的变体。我经常使用它在一系列远程主机上运行命令。我利用 bash 的大括号扩展来创建 for 循环,允许我创建非数字 for 循环。
Example:
例子:
I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:
我想在前端主机 1-5 和后端主机 1-3 上运行 uptime 命令:
% for host in {frontend{1..5},backend{1..3}}.mycompany.com
do ssh $host "echo -n $host; uptime"
done
I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.
我通常将此作为单行命令运行,在行的末尾使用分号,而不是上面更易读的版本。关键使用注意事项是大括号允许您指定要插入字符串的多个值(例如 pre{foo,bar}post 结果 in prefoopost, prebarpost)并允许使用双句点计数/序列(您可以使用 a. .z 等)。但是,双句点语法是 bash 3.0 的一个新特性;较早的版本将不支持此功能。
回答by terson
if you're intereased only in bash the "for(( ... ))" solution presented above is the best, but if you want something POSIX SH compliant that will work on all unices you'll have to use "expr" and "while", and that's because "(())" or "seq" or "i=i+1" are not that portable among various shells
如果您只对 bash 感兴趣,那么上面提供的“for((...))”解决方案是最好的,但是如果您想要符合 POSIX SH 标准且适用于所有 unices 的东西,您将不得不使用“expr”和"while",那是因为 "(())" 或 "seq" 或 "i=i+1" 在各种 shell 中不是那么可移植
回答by terson
I use variations of this all the time to process files...
我一直使用它的变体来处理文件......
for files in *.log; do echo "Do stuff with: $files"; echo "Do more stuff with: $files"; done;
对于 *.log 中的文件;do echo "用:$files"; echo "做更多的事情:$files"; 完毕;
If processing lists of files is what you're interested in, look into the -execdiroption for files.
如果您对处理文件列表感兴趣,请查看files的-execdir选项。