我有一个脚本读取包含 url 的文件,然后打印出 ip 地址。但是,我无法找到有关添加命令时管道为何阻塞的资源
cut -d" " -f4
在管道的末端。这是完整的命令。
for url in $(cat urls); do host $url; done | grep "has address" | cut -d" " -f4
输出是异步打印的,直到 grep 命令为止。 grep 之后的任何命令的输出都会被阻止,直到主机命令处理完所有 URL。谁能告诉我为什么会发生这种情况?
答案1
grep
如果不写入终端,则缓冲输出。您可以使用grep --line-buffered
立即输出每一行。考虑:
运行慢输出命令并 grep 到终端:
$ for i in {1..3}; do
> echo printing >&2
> echo to grep
> sleep 1
> done | grep to
printing
to grep
printing
to grep
printing
to grep
运行慢输出命令和 grep 进行剪切:
$ for i in {1..3}; do
> echo printing >&2
> echo to grep
> sleep 1
> done | grep to | cut -d" " -f1-2
printing
printing
printing
to grep
to grep
to grep
运行慢输出命令和 grep 使用选项进行剪切--line-buffered
:
$ for i in {1..3}; do
> echo printing >&2
> echo to grep
> sleep 1
> done | grep --line-buffered to | cut -d" " -f1-2
printing
to grep
printing
to grep
printing
to grep