Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminating a shell script bar from a script foo

I have a script foo which, if provided an argument start, starts, among other things a script bar in the background and exits - bar contains an infinite loop.

At a later stage, I want to call foo with argument stop and I would like that script bar, which still runs in the background stops running.

What is the text book way of achieving this?

like image 775
user695652 Avatar asked Dec 31 '25 17:12

user695652


1 Answers

In case multiple bar instances can run simultaneously, and foo stop should stop/kill them all, use pkill:

$ pkill bar

to kill all processes named bar.

In case only one bar instance is allowed to run, a solution with a "pidfile" would be viable.

In foo:

pidfile=/var/run/bar.pid

if ((start)); then
    if [ -e "$pidfile" ]; then
        echo "$pidfile exists."
        # clean-up, or simply abort...
        exit 1
    fi
    bar &
    echo $! >"$pidfile"
fi

if ((stop)); then
    if [ ! -e "$pidfile" ]; then
        echo "$pidfile not found."
        exit 1
    fi
    kill "$(<"$pidfile")"
    rm -f "$pidfile"
fi
like image 116
randomir Avatar answered Jan 04 '26 20:01

randomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!