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?
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?
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
.
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
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