kanka.dev
kanka.dev

Reputation: 67

How to kill another script in bash if it's already running

I have a hardware button on my Raspberry Pi. If I press it the script handle.sh is called which calls another script named do.sh. I want to kill do.sh if I press the button a second time. My desire is to toggle the script. First press run do.sh, second press exit this script.

My idea was to get the PID of do.sh. If there is already an instance of do.sh, handle.sh should kill the process of do.sh.

My pseudo code:

handle.sh

if do.sh not running {
    run do.sh
} else if do.sh is running {
    kill do.sh
    // do more stuff
}

do.sh

echo date
arecord -D hw:3,0 -f cd -r 44100 test.wav

Upvotes: 0

Views: 570

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 184965

Like this:

if pgrep -f do.sh &>/dev/null; then
    pkill -f do.sh
    // do more stuff
else
    ./do.sh
fi

Upvotes: 2

Related Questions