Feb 052011
 

tuxSmall tip of the day: Sometimes you need to run a program via cron or command line, but the important is that the program should not run if another istance it’s already active.

Or perhaps you have a process that every X minutes or hours crash and you need a wrapper that check for it’s existence and if not running restart it.


The fastest way to achieve this that i’ve found is :

if [ -z "$(pgrep foo)" ]
  then
     # foo is not running
  else
     # foo is running
fi

pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria to stdout. The nice thing is that pgrep take a lot of options, for example

-u Only match processes whose effective user ID is listed. Either the numerical or symbolical value may be used

-f The pattern is normally only matched against the process name. When -f is set, the full command line is used.

So for example you can use:

#!/bin/bash
 
if [ -z "$(pgrep -u mysql -f -- -port=3316 )" ]
  then
	/etc/init.d/mysqld start
  else
	echo "Process already running" >> /tmp/mysql.log
fi

To check if mysql is already running and if not start it.

Popular Posts:

Flattr this!

  One Response to “Check if program is already running with bash”

  1. Sto cercando proprio un script del genere….ma su debian non mi funziona.
    Devo controllare se un programma è in esecuzione e se non lo è deve lanciare la riga di comando per riavviarlo…help

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*