Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check in a bash script if something is running and exit if it is

Tags:

bash

scripting

I have a script that runs every 15 minutes but sometimes if the box is busy it hangs and the next process will start before the first one is finished creating a snowball effect. How can I add a couple lines to the bash script to check to see if something is running first before starting?

like image 337
Ryan Detzel Avatar asked May 29 '09 17:05

Ryan Detzel


People also ask

How do you check exit status in bash?

To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.

How do I check if a process is running in bash?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

How do you check the exit code?

Extracting the elusive exit code To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.


3 Answers

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

Example:

if pidof -x vim > /dev/null
then
    echo "Vim already running"
    exit 1
fi
like image 61
rodion Avatar answered Oct 19 '22 04:10

rodion


Why don't set a lock file ?

Something like

yourapp.lock

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

It could be done using

if [ -f yourapp.lock ]; then
echo "The process is already launched, please wait..."
fi
like image 33
Boris Guéry Avatar answered Oct 19 '22 03:10

Boris Guéry


In lieu of pidfiles, as long as your script has a uniquely identifiable name you can 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 ...
like image 3
allaryin Avatar answered Oct 19 '22 02:10

allaryin