Check if a process is not running and then run it

Asked

Viewed 7,306 times

3

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

How to do this on linux?

3 answers

5


There are several ways to do this. One of them is by using the 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 that into one Shell Script:

#!/bin/bash

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

Taken from How to determine whether a process is running or not and make use it to make a conditional shell script?

Important note:

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

pgrep ged

Return any process you have ged in the name.

In turn:

pgrep -x gedit

Would only return processes that are exactly gedit.

3

You can create a shell script that returns how many processes are running. Of course 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

0

Starting a process once, opening a session in the terminal. Place at the end of the file ~/. bashrc:

pid=$(pgrep -x redshift)

if [ "$pid" = "" ]
then
  redshift &
fi

Browser other questions tagged

You are not signed in. Login or sign up in order to post.