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

Che*_*tan 6 bash scripting exit terminate

我有以下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
Run Code Online (Sandbox Code Playgroud)

出于某种原因,它正在回响launchd message,等待整整5秒,然后退出.

为什么会发生这种情况,如何让它在回声之后立即退出launchd message

Ign*_*ams 9

由于您正在使用管道,因此while循环正在子shell中运行.而是在主shell中运行它.

#!/bin/bash

while ...
do
   ...
done < <(tail ...)
Run Code Online (Sandbox Code Playgroud)