Search code examples
bashscriptingexitterminate

Bash script not exiting immediately when `exit` is called


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?


Solution

  • 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 ...)