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

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

    Answered a million times already, but another way, without the need for external dependencies:

    LOCK_FILE="/var/lock/$(basename "$0").pid"
    trap "rm -f ${LOCK_FILE}; exit" INT TERM EXIT
    if [[ -f $LOCK_FILE && -d /proc/`cat $LOCK_FILE` ]]; then
       // Process already exists
       exit 1
    fi
    echo $$ > $LOCK_FILE
    

    Each time it writes the current PID ($$) into the lockfile and on script startup checks if a process is running with the latest PID.

提交回复
热议问题