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

Time:12-16

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

CodePudding user response:

Like this:

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