Bash How to know if a Process is Running

Bash How to know if a Process is Running

In this article, assume that we are looking for a process named “bash”. If you are not using a different shell, the bash process is running probably all of you.

If you want to see just PID (Process ID), you can use pgrep. If there is more than one process called bash, the output will be multi-line. If there is no process called bash, nothing is written to screen:

pgrep bash

What if you want to write some output if bash is running? In this example, pgrep finds a process called “bash”, redirects all output to /dev/null (nowhere). If pgrep return zero exit code, echo “The bash is running” will be executed:

pgrep bash 1>/dev/null 2>&1 && echo "The bash is running"

This example output “The bash is not running”, if bash is not running, you can use:

pgrep bash 1>/dev/null 2>&1 || echo "The bash is not running"

If you want to see, all processes that are running, there are also possible to do that in the traditional way. In the next example, ps aux is redirected to grep. Grep will filter lines that end ($) with bash:

ps aux | grep bash$

The second column of output is PID (Process ID). It is useful when you want to kill processes.

Command ps has ‘-o’ (overloaded) flag which shows you information about processes. One of the options is the stat option. Example:

ps -o comm, stat

Output: COMMAND STAT
bash Ss
ps R+

If the process is running it has the capital letter R or S.

Leave a Comment