What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?
相关问题
- How to get the return code of a shell script in lu
- JQ: Select when attribute value exists in a bash a
- Invoking Mirth Connect CLI with Powershell script
- Emacs shell: save commit message
- bash print whole line after splitting line with if
相关文章
- 使用2台跳板机的情况下如何使用scp传文件
- In IntelliJ IDEA, how can I create a key binding t
- Check if directory exists on remote machine with s
- shell中反引号 `` 赋值变量问题
- How get the time in milliseconds in FreeBSD?
- Reverse four length of letters with sed in unix
- Launch interactive SSH bash session from PHP
- BASH: Basic if then and variable assignment
Really quick and really dirty? This one-liner on the top of your script will work:
Of course, just make sure that your script name is unique. :)
Some unixes have
lockfile
which is very similar to the already mentionedflock
.From the manpage:
The existing answers posted either rely on the CLI utility
flock
or do not properly secure the lock file. The flock utility is not available on all non-Linux systems (i.e. FreeBSD), and does not work properly on NFS.In my early days of system administration and system development, I was told that a safe and relatively portable method of creating a lock file was to create a temp file using
mkemp(3)
ormkemp(1)
, write identifying information to the temp file (i.e. PID), then hard link the temp file to the lock file. If the link was successful, then you have successfully obtained the lock.When using locks in shell scripts, I typically place an
obtain_lock()
function in a shared profile and then source it from the scripts. Below is an example of my lock function:The following is an example of how to use the lock function:
Remember to call
clean_up
at any exit points in your script.I've used the above in both Linux and FreeBSD environments.
Here is a more elegant, fail-safe, quick
& dirtymethod, combining the answers provided above.Usage
Script File
sh_lock_functions.sh
Usage example
sh_lock_usage_example.sh
Features
If flock's limitations, which have already been described elsewhere on this thread, aren't an issue for you, then this should work:
Use
flock(1)
to make an exclusive scoped lock a on file descriptor. This way you can even synchronize different parts of the script.This ensures that code between
(
and)
is run only by one process at a time and that the process doesn’t wait too long for a lock.Caveat: this particular command is a part of
util-linux
. If you run an operating system other than Linux, it may or may not be available.