Check if a process is not running and then run it

3

I need to run a given command via terminal. However, this command should only be run if the process is not running. If it is running, you do not need to do any other operation.

How to do this in linux?

    
asked by anonymous 18.01.2016 / 17:35

3 answers

5

There are several ways to do this. One of them is using pgrep :

pgrep gedit

If gedit is running, a number will be returned.

17805

This number is the process ID (PID). This number obviously changes.

Combining this into a Shell Script :

#!/bin/bash

# Verifica se o gedit está sendo executado
if pgrep "gedit" > /dev/null
then
    echo "Executando"
else
    echo "Parado"
fi

Retrieved from How to determine if a process is running or not and make use of it to make a conditional shell script?

Important Note:

To ensure that the search is by the exact process name, use the -x option, for example:

pgrep ged

Would return any process that has ged in the name.

In turn:

pgrep -x gedit

I would only return processes that are exactly gedit .

    
18.01.2016 / 17:42
3

You can create a shell script that returns how many processes are running. Of course the else can be deleted.

#!/bin/sh
# Verificacao se servico esta online

qtde=$(ps aux | grep "mysqld" | wc -l)

if test "$qtde" = "1"
then
  echo "MySQL is offline";
  echo "Starting...";
  /etc/init.d/mysql stop;
  /etc/init.d/mysql start;
else
  echo "MySQLd is online." ;
  echo "Nothing to do.";
fi
    
18.01.2016 / 17:42
0

Starting a process only once when opening a session on the terminal. Place at the end of the ~ / .bashrc file:

pid=$(pgrep -x redshift)

if [ "$pid" = "" ]
then
  redshift &
fi
    
13.09.2017 / 14:35