[ACCEPTED]-How to check in a bash script if something is running and exit if it is-scripting

Accepted answer
Score: 13

You can use pidof -x if you know the process name, or 1 kill -0 if you know the PID.

Example:

if pidof -x vim > /dev/null
then
    echo "Vim already running"
    exit 1
fi
Score: 5

Why don't set a lock file ?

Something like 3

yourapp.lock

Just remove it when you process 2 is finished, and check for it before to 1 launch it.

It could be done using

if [ -f yourapp.lock ]; then
echo "The process is already launched, please wait..."
fi
Score: 3
pgrep -f yourscript >/dev/null && exit

0

Score: 3

In lieu of pidfiles, as long as your script 2 has a uniquely identifiable name you can 1 do something like this:

#!/bin/bash
COMMAND=$0
# exit if I am already running
RUNNING=`ps --no-headers -C${COMMAND} | wc -l`
if [ ${RUNNING} -gt 1 ]; then
  echo "Previous ${COMMAND} is still running."
  exit 1
fi
... rest of script ...
Score: 3

This is how I do it in one of my cron jobs

lockfile=~/myproc.lock
minutes=60
if [ -f "$lockfile" ]
then
  filestr=`find $lockfile -mmin +$minutes -print`
  if [ "$filestr" = "" ]; then
    echo "Lockfile is not older than $minutes minutes! Another $0 running. Exiting ..."
    exit 1
  else
    echo "Lockfile is older than $minutes minutes, ignoring it!"
    rm $lockfile
  fi
fi

echo "Creating lockfile $lockfile"
touch $lockfile

and 1 delete the lock file at the end of the script

echo "Removing lock $lockfile ..."
rm $lockfile
Score: 2

For a method that does not suffer from parsing 1 bugs and race conditions, check out:

Score: 2

I had recently the same question and found 1 from above that kill -0 is best for my case:

echo "Starting process..."
run-process > $OUTPUT &
pid=$!
echo "Process started pid=$pid"
while true; do
    kill -0 $pid 2> /dev/null || { echo "Process exit detected"; break; }
    sleep 1
done
echo "Done."
Score: 1

To expand on what @bgy says, the safe atomic way 10 to create a lock file if it doesn't exist 9 yet, and fail if it doesn't, is to create 8 a temp file, then hard link it to the standard 7 lock file. This protects against another 6 process creating the file in between you 5 testing for it and you creating it.

Here 4 is the lock file code from my hourly backup 3 script:

echo $$ > /tmp/lock.$$
if ! ln /tmp/lock.$$ /tmp/lock ; then 
        echo "previous backup in process"
        rm /tmp/lock.$$
        exit
fi

Don't forget to delete both the lock 2 file and the temp file when you're done, even 1 if you exit early through an error.

Score: 1

Use this script:

FILE="/tmp/my_file"
if [ -f "$FILE" ]; then
   echo "Still running"
   exit
fi
trap EXIT "rm -f $FILE"
touch $FILE

...script here...

This script will create 1 a file and remove it on exit.

More Related questions