0

I need some help. I'm having a script 'Script 1', which will call 'Script 2' to run in background which checks something periodically. But I want the Script 2 to get started only once, even Script 1 is called multiple times. Is there a way to do it?

It would be even more helpful, if someone suggests some commands to achieve this.

Thanks in advance

iMSivam
  • 151
  • 1
  • 1
  • 10
  • possible duplicate of [Shell script: Ensure that script isn't executed if already running](http://stackoverflow.com/questions/4768860/shell-script-ensure-that-script-isnt-executed-if-already-running) – Christian.K Sep 25 '12 at 05:52
  • Duplicate of : http://stackoverflow.com/questions/185451/quick-and-dirty-way-to-ensure-only-one-instance-of-a-shell-script-is-running-at – Rohit Vipin Mathews Sep 25 '12 at 10:08

1 Answers1

1

Sure, you can put something like this at the top of Script2:

if [[ -f /tmp/Script2HasRun ]] ; then
    exit
fi
touch /tmp/Script2HasRun

That will stop Script2 from ever running again by using a sentinel file, unless the file is deleted of course, and it probably will be at some point since it's in /tmp.

So you probably want to put it somewhere else where it can be better protected.

If you don't want to stop it from ever running again, you need some mechanism to delete the sentinel file.

For example, if your intent is to only have one copy running at a time:

if [[ -f /tmp/Script2IsRunning ]] ; then
    exit
fi
touch /tmp/Script2IsRunning
# Do whatever you have to do.
rm -f /tmp/Script2IsRunning

And keep in mind there's a race condition in there that could result in two copies running. There are ways to mitigate that as well by using the content as well as the existence, something like:

if [[ -f /tmp/Script2IsRunning ]] ; then
    exit
fi
echo $$ >/tmp/Script2IsRunning
sleep 1
if [[ "$(cat /tmp/Script2IsRunning 2>/dev/null)" != $$ ]] ; then
    exit
fi
# Do whatever you have to do.
rm -f /tmp/Script2IsRunning

There are more levels of protection beyond that but they become complex, and I usually find that suffices for most things.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953