调用“exit”时,Bash 脚本不会立即退出

发布于 2024-09-29 05:49:36 字数 353 浏览 1 评论 0原文

我有以下 bash 脚本:

tail -F -n0 /private/var/log/system.log | while read line 
do
    if [ ! `echo $line | grep -c 'launchd'` -eq 0 ]; then
        echo 'launchd message'
        exit 0
    fi
done

由于某种原因,它正在回显 launchd 消息,等待整整 5 秒,然后然后退出。

为什么会发生这种情况以及如何让它在回显 launchd 消息后立即退出?

I have the following bash script:

tail -F -n0 /private/var/log/system.log | while read line 
do
    if [ ! `echo $line | grep -c 'launchd'` -eq 0 ]; then
        echo 'launchd message'
        exit 0
    fi
done

For some reason, it is echoing launchd message, waiting for a full 5 seconds, and then exiting.

Why is this happening and how do I make it exit immediately after it echos launchd message?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡水深流 2024-10-06 05:49:36

由于您使用的是管道,因此 while 循环正在子 shell 中运行。相反,请在主 shell 中运行它。

#!/bin/bash

while ...
do
   ...
done < <(tail ...)

Since you're using a pipe, the while loop is being run in a subshell. Run it in the main shell instead.

#!/bin/bash

while ...
do
   ...
done < <(tail ...)
蓝海似她心 2024-10-06 05:49:36

正如 Ignacio 所指出的,你的尾巴 | while 创建一个子shell。延迟是因为它在一切关闭之前等待下一行写入日志文件。

如果您不想使用进程替换,您可以在 exit 命令之前添加此行:

kill -SIGPIPE $

不幸的是,我不知道有什么方法可以使用此方法来控制退出代码。它将是 141,即 128 + 13(SIGPIPE 的信号编号)。

如果您试图使一个守护进程的启动依赖于另一个守护进程的启动,可能有更好的方法来做到这一点。

顺便说一句,如果您确实正在编写 Bash 脚本(必须使用 <() 进程替换),则可以编写 if像这样:if [[ $line == *launchd* ]]

As indicated by Ignacio, your tail | while creates a subshell. The delay is because it's waiting for the next line to be written to the log file before everything closes.

You can add this line immediately before your exit command if you'd prefer not using process substitution:

kill -SIGPIPE $

Unfortunately, I don't know of any way to control the exit code using this method. It will be 141 which is 128 + 13 (the signal number of SIGPIPE).

If you're trying to make the startup of a daemon dependent on another one having started, there's probably a better way to do that.

By the way, if you're really writing a Bash script (which you'd have to be to use <() process substitution), you can write your if like this: if [[ $line == *launchd* ]].

情栀口红 2024-10-06 05:49:36

您还可以使用告诉退出代码退出子 shell,然后测试“$?”的值。为了获得您正在寻找的相同效果:

tail -F -n0 /private/var/log/system.log | while read line 
do
    if [ ! `echo $line | grep -c 'launchd'` -eq 0 ]; then
        echo 'launchd message'
        exit 10
    fi
done
if [ $? -eq 10 ]; then exit 0; fi

You can also exit the subshell with a tell-tale exit code and then test the value of "$?" to get the same effect you're looking for:

tail -F -n0 /private/var/log/system.log | while read line 
do
    if [ ! `echo $line | grep -c 'launchd'` -eq 0 ]; then
        echo 'launchd message'
        exit 10
    fi
done
if [ $? -eq 10 ]; then exit 0; fi
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文