1

I am trying to determine whether another instance of my bash-script is running, and wait until this instance is the only one, then proceed with other stuff.

I tried the following:

#!/bin/bash

while [[ $(ps aux | grep $0 | wc -l) > 2 ]]; do
    echo another instance already running, waiting. 
    # Next line is for debugging:
    ps aux | grep $0 | wc -l
    sleep 1
done

echo I am now the only instance, ready to proceed

# do stuff

I also tried it with `expr $(ps aux | grep $0 | wc -l)`.

Both go the while loop even if the output of the command within the while loop is 2 (which is the output I expect when only running one instance, since ps aux counts the grep as well).

What am I doing wrong here? Any other suggestions as to how to approach this?

Extra comment: I know that in order for that to work in general, I will have to end the script if I detect more than two running instances, otherwise they might all get stuck in the while loop forever. Once I get the loop running correctly, I will add this before the loop. Also, I will make sure the script is run by its full path, so using $0 won't lead to confusion.

maddingl
  • 197
  • 4
  • 20
  • 1
    A possible duplicate of [this question](https://stackoverflow.com/questions/2530114/continue-script-if-only-one-instance-is-running) or [this other one](https://stackoverflow.com/questions/2530114/continue-script-if-only-one-instance-is-running). – LMC Mar 27 '18 at 23:53
  • 1
    @LuisMuñoz - both links you posted are the same -- intentional? It looks like you intended [Quick-and-dirty way to ensure only one instance of a shell script is running at a time](https://stackoverflow.com/questions/185451/quick-and-dirty-way-to-ensure-only-one-instance-of-a-shell-script-is-running-at) for one of them. – David C. Rankin Mar 27 '18 at 23:55
  • My bad sorry, this is the other one https://stackoverflow.com/questions/16807876/shell-script-execution-check-if-it-is-already-running-or-not – LMC Mar 28 '18 at 00:00
  • The much, *much* more reliable way to do this is to leverage your operating system's locking capabilities. The better answers to [What is the best way to ensure only one instance of a bash script is running at a time?](https://stackoverflow.com/questions/1715137/what-is-the-best-way-to-ensure-only-one-instance-of-a-bash-script-is-running) do this, for example. It's also much more efficient -- `flock` will immediately be informed when any other lock is cleared, instead of needing to check the process table over-and-over. – Charles Duffy Mar 28 '18 at 00:09
  • Checking the process table over-and-over is also prone to race conditions -- keep in mind that when you run `ps`, by the time you get a result, you're inspecting a view of the past, not the present. It's a bad approach in general. – Charles Duffy Mar 28 '18 at 00:11
  • Thank you. I ended up using [this](https://stackoverflow.com/a/1985512/8772658), and it works perfectly :) – maddingl Mar 28 '18 at 09:48

0 Answers0