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.