How do I make sure my bash script isn't already running?

后端 未结 13 913
無奈伤痛
無奈伤痛 2020-12-31 05:56

I have a bash script I want to run every 5 minutes from cron... but there\'s a chance the previous run of the script isn\'t done yet... in this case, i want the new run to j

13条回答
  •  既然无缘
    2020-12-31 06:24

    I was trying to solve this problem today and I came up with the below:

    COMMAND_LINE="$0 $*"
    JOBS=$(SUBSHELL_PID=$BASHPID; ps axo pid,command | grep "${COMMAND_LINE}" | grep -v $$ | g    rep -v ${SUBSHELL_PID} | grep -v grep)
    if [[ -z "${JOBS}" ]]
    then
        # not already running
    else
        # already running
    fi
    

    This relies on $BASHPID which contains the PID inside a subshell ($$ in the subshell is the parent pid). However, this relies on Bash v4 and I needed to run this on OSX which has Bash v3.2.48. I ultimately came up with another solution and it is cleaner:

    JOBS=$(sh -c "ps axo pid,command | grep \"${COMMAND_LINE}\" | grep -v grep | grep -v $$")
    

提交回复
热议问题