Quick-and-dirty way to ensure only one instance of a shell script is running at a time

前端 未结 30 2460
忘掉有多难
忘掉有多难 2020-11-22 02:57

What\'s a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 03:07

    Use flock(1) to make an exclusive scoped lock a on file descriptor. This way you can even synchronize different parts of the script.

    #!/bin/bash
    
    (
      # Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds
      flock -x -w 10 200 || exit 1
    
      # Do stuff
    
    ) 200>/var/lock/.myscript.exclusivelock
    

    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.

提交回复
热议问题