Ubuntu – How can Bash script kill “sleeping” version of itself already running

bashprocessscripts

Edit From the comments below I wrote a confusing/misleading introduction so I'm rewriting it.

I have a bash script called "lock screen timer" that can be clicked on the desktop. After 30 minutes it locks the screen and the user has to enter their password to unlock the screen. However if the user changes their mind, or they want to reset the timer, they should be able to click the desktop shortcut again and it should kill the previouly running job which is sleeping and counting down.

I've done a little trial and error so far and hit a road-block.

The relevant code snippet is:

pgrep tv-timer > ~/tv-timer.log
PID=$$ # Current Process ID

Using cat ~/tv-timer.log:

16382
20711

One of these is equal to "$PID" above but the other is a previously running copy which I want to use kill #####.

What's the best way of figuring out which one <> "$PID" and killing it?

The first time the script is run there is only one entry equal to "$PID" which I don't want to kill.

Thanks for your help!


The proposed duplicate (Prevent duplicate script run at the sametime) is a problem within Parent and Child processes. Accepted answers are long and complicated involving wrapper scripts and/or multiple lines of code.

The solution sought here is one line of new code!

Indeed the accepted-elect answer here is based on duplicate OP attempt THAT DOES NOT WORK THERE!

Best Answer

Please, change the line:

pgrep tv-timer | grep -v $$ > ~/tv-timer2.log

into this:

pgrep tv-timer | grep -v ^$$$ > ~/tv-timer2.log

In fact, if one tv-timer prosesses has, say, PID=26019 and should $$ be 6019, then grep would yield an empty string, which is not what you want.

Related Question