Skip to content

Instantly share code, notes, and snippets.

@nttuyen
Forked from darth-veitcher/bash-pid.md
Created April 30, 2019 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nttuyen/ad6da85c685ef0053b3fc2453216b4f6 to your computer and use it in GitHub Desktop.
Save nttuyen/ad6da85c685ef0053b3fc2453216b4f6 to your computer and use it in GitHub Desktop.
Bash Script PID file locking

Pattern below allows for a bash script to be called via, say, cron and check to see if it is already running.

Useful for things like rsync tasks.

PIDFILE=/var/run/myscriptname.pid

if [ -f $PIDFILE ]
then
  PID=$(cat $PIDFILE)
  ps -p $PID > /dev/null 2>&1
  if [ $? -eq 0 ]
  then
    echo "Process already running"
    exit 1
  else
    ## Process not found assume not running
    echo $$ > $PIDFILE
    if [ $? -ne 0 ]
    then
      echo "Could not create PID file"
      exit 1
    fi
  fi
else
  echo $$ > $PIDFILE
  if [ $? -ne 0 ]
  then
    echo "Could not create PID file"
    exit 1
  fi
fi


# Main script ... Do work here

...

# End

rm $PIDFILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment