Timeline for How to make sure only one instance of a bash script runs?
Current License: CC BY-SA 3.0
13 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Oct 18, 2022 at 18:13 | comment | added | Brent212 | I've always wondered why people add the "x" in string comparisons like this, when omitting it like this should work fine: [ "$(cat /tmp/lock.file)" == "$$" ] || exit | |
| Sep 19, 2012 at 8:13 | comment | added | nsg | Axel: Sure, sounds like a good idea. I Also recommend Bruce Ediger's mkdir based answer. | |
| Sep 18, 2012 at 13:30 | comment | added | Axel Knauf |
Does it make sense to add a trap for SIGINT, SIGTERM etc to make sure your lock file gets cleaned up in case somebody kills the current run (explicitly with Ctrl-C or during shutdown)?
|
|
| Sep 18, 2012 at 11:51 | history | edited | nsg | CC BY-SA 3.0 |
added 97 characters in body
|
| Sep 18, 2012 at 11:49 | comment | added | Tobias Kienzler |
here's a lockfile answer at SO. Maybe in combination with the mkdir answer, race conditions and stalenes checks can be included...
|
|
| Sep 18, 2012 at 11:46 | comment | added | nsg | manatwork: nice idea, I will update my answer. | |
| Sep 18, 2012 at 11:45 | comment | added | nsg | I have never used lsof for this purpose, I this it should work. Note that lsof is really slow in my system (1-2 sec) and most likely there is a lot of time for race conditions. | |
| Sep 18, 2012 at 11:41 | comment | added | manatwork |
You can diminish the race condition by writing your $$ in the lock file. Then sleep for a short interval and read it back. If the PID is still yours, you successfully acquired the lock. Needs absolutely no additional tools.
|
|
| Sep 18, 2012 at 11:34 | comment | added | Tobias Kienzler |
They shouldn't be relevant in my case either, but it's something one should keep in mind. Maybe using lsof $0 isn't bad, either?
|
|
| Sep 18, 2012 at 11:33 | history | edited | nsg | CC BY-SA 3.0 |
added 60 characters in body
|
| Sep 18, 2012 at 11:32 | comment | added | nsg | ops :) Yes, race conditions is a problem in my example, I usually write hourly or daily cron jobs and race conditions are rare. | |
| Sep 18, 2012 at 11:28 | comment | added | Tobias Kienzler | (I think you forgot to create the lock file) What about race conditions? | |
| Sep 18, 2012 at 11:18 | history | answered | nsg | CC BY-SA 3.0 |