How to make sure only one instance of a Bash script is running at a time?

前端 未结 6 1880
时光取名叫无心
时光取名叫无心 2021-02-08 00:54

I want to make a sh script that will only run at most once at any point.

Say, if I exec the script then I go to exec the script again, how do I make it so that if the f

6条回答
  •  感情败类
    2021-02-08 01:13

    I think you need to use lockfile command. See using lockfiles in shell scripts (BASH) or http://www.davidpashley.com/articles/writing-robust-shell-scripts.html.

    The second article uses "hand-made lock file" and shows how to catch script termination & releasing the lock; although using lockfile -l will probably be a good enough alternative for most cases.

    Example of usage without timeout:

    lockfile script.lock
    
    rm -f script.lock
    

    Will ensure that any second script started during this one will wait indefinitely for the file to be removed before proceeding.

    If we know that the script should not run more than X seconds, and the script.lock is still there, that probably means previous instance of the script was killed before it removed script.lock. In that case we can tell lockfile to force re-create the lock after a timeout (X = 10 below):

    lockfile -l 10 /tmp/mylockfile
    
    rm -f /tmp/mylockfile
    

    Since lockfile can create multiple lock files, there is a parameter to guide it how long it should wait before retrying to acquire the next file it needs (- and -r ). There is also a parameter -s for wait time when the lock has been removed by force (which kind of complements the timeout used to wait before force-breaking the lock).

提交回复
热议问题