user9201277
user9201277

Reputation:

Terminate indefinitely running sub-command - inotify

Imagine a scenario like so, where inotify calls another script which goes on forever

while inotifywait -e close_write ./<sample-file>; do 
    ./file.sh
done

Content file.sh:

while true; do
    sleep 5;
    echo "sample message";
done

Is there a way I can terminate the execution of the file.sh whenever sample-file gets updated?

Thanks!

Upvotes: 0

Views: 117

Answers (1)

Shawn
Shawn

Reputation: 52336

You can run file.sh in the background, and keep track of it's running already or not. If it is, kill it before running it again. Example:

#!/bin/sh
bgpid=
trap 'kill $bgpid' 0 2 3 15 # Kill the background process when the parent exits
while inotifywait -e open ./input.txt; do
    if [ -n "$bgpid" ]; then
        echo "Killing existing file.sh on pid $bgpid"
        kill $bgpid
        bgpid=
    fi
    ./file.sh &
    bgpid=$!
done

Upvotes: 0

Related Questions