bash how to know if a process is running


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

If you want to see just PID (Process ID), you can use pgrep. If there are more than one process that called bash, 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 process called "bash", redirect 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 by traditional way. In 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 option is stat option. Example:

ps -o comm,stat

bash Ss
ps R+

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

Was this information helpful to you? You have the power to keep it alive.
Each donated € will be spent on running and expanding this page about UNIX Shell.