bash 将字符串列表通过管道输送到 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29560198/
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
Pipe a list of strings to for loop
提问by rubo77
How do I pass a list to for
in bash?
如何for
在 bash 中传递列表?
I tried
我试过
echo "some
different
lines
" | for i ; do
echo do something with $i;
done
but that doesn't work. I also tried to find an explanation with man
but there is no man for
但这不起作用。我也试图找到一个解释,man
但没有man for
EDIT:
编辑:
I know, I could use while
instead, but I think I once saw a solution with for
where they didn't define the variable but could use it inside the loop
我知道,我可以while
改用,但我想我曾经看到过一个解决方案,for
其中没有定义变量但可以在循环中使用它
回答by Aaron Digulla
This might work but I don't recommend it:
这可能有效,但我不建议这样做:
echo "some
different
lines
" | for i in $(cat) ; do
...
done
$(cat)
will expand everything on stdin
but if one of the lines of the echo
contains spaces, for
will think that's two words. So it might eventually break.
$(cat)
将扩展所有内容,stdin
但如果其中一行echo
包含空格,for
则会认为这是两个词。所以它最终可能会破裂。
If you want to process a list of words in a loop, this is better:
如果要在循环中处理单词列表,最好这样做:
a=($(echo "some
different
lines
"))
for i in "${a[@]}"; do
...
done
Explanation: a=(...)
declares an array. $(cmd...)
expands to the output of the command. It's still vulnerable for white space but if you quote properly, this can be fixed.
解释:a=(...)
声明一个数组。$(cmd...)
扩展到命令的输出。它仍然容易受到空白区域的影响,但如果您正确引用,则可以修复。
"${a[@]}"
expands to a correctly quoted list of elements in the array.
"${a[@]}"
扩展为数组中正确引用的元素列表。
Note: for
is a built-in command. Use help for
(in bash) instead.
注意:for
是一个内置命令。改用help for
(在 bash 中)。
回答by Tom Fenech
for
iterates over a list of words, like this:
for
遍历单词列表,如下所示:
for i in word1 word2 word3; do echo "$i"; done
use a while read
loop to iterate over lines:
使用while read
循环遍历行:
echo "some
different
lines" | while read -r line; do echo "$line"; done
Here is some useful readingon reading lines in bash.
回答by Caduchon
This seems to work :
这似乎有效:
for x in $(echo a b c); do
echo $x
done
回答by rubo77
This is not a pipe, but quite similar:
这不是管道,但非常相似:
args="some
different
lines";
set -- $args;
for i ; do
echo $i;
done
cause for
defaults to $@
if no in seq
is given.
如果没有给出for
,$@
则原因默认为in seq
。
maybe you can shorten this a bit somehow?
也许你可以以某种方式缩短一点?