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

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

    An example with flock(1) but without subshell. flock()ed file /tmp/foo is never removed, but that doesn't matter as it gets flock() and un-flock()ed.

    #!/bin/bash
    
    exec 9<> /tmp/foo
    flock -n 9
    RET=$?
    if [[ $RET -ne 0 ]] ; then
        echo "lock failed, exiting"
        exit
    fi
    
    #Now we are inside the "critical section"
    echo "inside lock"
    sleep 5
    exec 9>&- #close fd 9, and release lock
    
    #The part below is outside the critical section (the lock)
    echo "lock released"
    sleep 5
    

提交回复
热议问题