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

前端 未结 30 3237
忘掉有多难
忘掉有多难 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:27

    You need an atomic operation, like flock, else this will eventually fail.

    But what to do if flock is not available. Well there is mkdir. That's an atomic operation too. Only one process will result in a successful mkdir, all others will fail.

    So the code is:

    if mkdir /var/lock/.myscript.exclusivelock
    then
      # do stuff
      :
      rmdir /var/lock/.myscript.exclusivelock
    fi
    

    You need to take care of stale locks else aftr a crash your script will never run again.

提交回复
热议问题