Reputation: 7844
I am trying to automatically check if a process is running or not and have to perform next steps accordingly. I had written a bash script but it doesn't seem to work.
if ps aux | grep [M]yProcessName > /dev/null
then
echo "Running"
else
echo "Not running"
fi
Is my if
statement wrongly used?
Upvotes: 16
Views: 69493
Reputation: 111
Just to explicitly mention a way this answer alluded to, pgrep
is the best way to do this by process name:
pgrep [M]yProcessName
If a process whose name matches "[M]yProcessName" is running, pgrep
will print its PID to stdout and will exit with code 0
. Otherwise, it will print nothing and exit with code 1
.
Upvotes: 1
Reputation: 53
SMBD=$(pidof smbd)
if [ "$SMBD" == "" ];
then
/etc/init.d/samba start;
else
/etc/init.d/samba restart;
fi
Upvotes: 1
Reputation: 1414
processid =$(ps aux | grep 'ProcessName' | grep -v grep| awk '{print $2}')
The above command will give you the process id. Assign that process id to a variable and do this -->
if cat /proc/$processid/status | grep "State: R (running)" > /dev/null
then
echo "Running"
else
echo "Not running"
fi
Upvotes: 2
Reputation: 43
There is a solution:
if [ "$(ps aux | grep "what you need" | awk '{print $11}')" == "grep" ]; then ... elif [ ... ]; then ... else ... fi
This works fine in Debian 6. '{print $11}' is needed, because the sytem treats grep as a process as well
Upvotes: 2
Reputation: 79
On my system, ps aux | grep ProcessName
always get a line of that grep process like:
edw4rd 9653 0.0 0.0 4388 832 pts/1 S+ 21:09 0:00 grep --color=auto ProcessName
So, the exit status is always 0. Maybe that's why your script doesn't work.
Upvotes: 0
Reputation: 1
You don't want to know if a particular process (of known pid) is running (this can be done by testing if /proc/1234/
exists for pid 1234) but if some process is running a given command (or a given executable).
Notice that the kill(2) syscall can be portably used to check if a given process is running (with a 0 signal, e.g. kill(pid,0)
). From inside a program, this is a common way to check that a process of known pid is still existing and running (or waiting).
You could use the pidof
command to find the processes running some executable, e.g. pidof zsh
to find all the zsh
processes. You could also use killall -s 0 zsh
And you might be interested by the pgrep
utility and the /proc
filesystem.
Upvotes: 12
Reputation: 23
Using -z to check if a string is empty or not, something like this could work:
line=$(ps aux | grep [M]yProcessName)
if [ -z "$line" ]
then
echo "Not Running"
else
echo $line > /dev/null
echo "Rinnung"
fi
Upvotes: 2