gpt4 book ai didi

linux - Bash while 循环意外停止

转载 作者:IT王子 更新时间:2023-10-29 00:35:05 25 4
gpt4 key购买 nike

我正在分析两个具有我不理解的行为的脚本:

#/bin/bash
tijd=${1-60}
oud=`ls -l $MAIL`
while : ; do
nieuw=`ls -l $MAIL`
echo $oud $nieuw
sleep $tijd
done | { read a b rest ; echo $a ; echo $b ; echo $rest ; }

此脚本中的 while 循环在一次迭代后停止。

#/bin/bash
tijd=${1-60}
oud=`ls -l $MAIL`
while : ; do
nieuw=`ls -l $MAIL`
echo $oud $nieuw
sleep $tijd
done | cat

此脚本中的 while 循环是无限的。

有什么区别?我认为这是管道和支架的问题,但我无法解释。

最佳答案

您在 pipe 之后使用 read 的循环在第一次迭代后终止,因为调用了 SIGPIPE 信号,这发生在管道写入管道的 LHS其输出未被读取,因为 RHS 上没有围绕 read 的 while 循环)。 YOur example with cat does not exit because cat continuously reads from input where as read terminates 阅读一行后。

要理解这种行为,首先要减少你的例子:

while : ; do pwd; done | { read -r line; echo $line; }
/Users/admin

因此 read 在第一行之后终止。要验证此启用 pipefail 使用:

set -o pipefail

并检查退出状态:

while : ; do pwd; done | { read -r line; echo "$line"; }
echo $?
141

存在状态 141 是由于 SIGPIPE


要解决此问题,请在 while 循环内更改管道 RHS 上的 read:

while : ; do pwd; sleep 5; done | { while read -r line; do echo "$line"; done; }
/Users/admin
/Users/admin
/Users/admin

现在您根本看不到命令​​退出,因为 while read 不断从管道的 LHS 捕获所有数据。

关于linux - Bash while 循环意外停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30423315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com