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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:45:40  来源:igfitidea点击:

Pipe a list of strings to for loop

bash

提问by rubo77

How do I pass a list to forin 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 manbut there is no man for

但这不起作用。我也试图找到一个解释,man但没有man for

EDIT:

编辑:

I know, I could use whileinstead, but I think I once saw a solution with forwhere 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 stdinbut if one of the lines of the echocontains spaces, forwill 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: foris a built-in command. Use help for(in bash) instead.

注意:for是一个内置命令。改用help for(在 bash 中)。

回答by Tom Fenech

foriterates over a list of words, like this:

for遍历单词列表,如下所示:

for i in word1 word2 word3; do echo "$i"; done

use a while readloop 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.

这里有一些关于在 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 fordefaults to $@if no in seqis given.

如果没有给出for$@则原因默认为in seq

maybe you can shorten this a bit somehow?

也许你可以以某种方式缩短一点?