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

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

    If flock's limitations, which have already been described elsewhere on this thread, aren't an issue for you, then this should work:

    #!/bin/bash
    
    {
        # exit if we are unable to obtain a lock; this would happen if 
        # the script is already running elsewhere
        # note: -x (exclusive) is the default
        flock -n 100 || exit
    
        # put commands to run here
        sleep 100
    } 100>/tmp/myjob.lock 
    

提交回复
热议问题