Bash check if process is running or not on Linux / Unix

You can use the ps command to check if a process is running or not on Linux/Unix. The ps command lists all running processes on the system.

To check if a specific process is running, you can use the grep command to filter the output of the ps command.

For example, to check if the process “nginx” is running, you can use the following command:

ps aux | grep -E '[n]ginx'

This command lists all processes and then filters the output to show only the lines that contain the string “nginx”. The -E option is used for extended regular expressions and the [n] tells grep to match the character ‘n’ at the beginning of the process name, it’s used to avoid matching the grep process itself.

You can also use the pgrep command to check if a process is running or not. The pgrep command takes the process name as an argument and returns the process ID (PID) if the process is running.

For example, to check if the process “nginx” is running, you can use the following command:

pgrep nginx

If the process is running, the command will return the PID of the process. If the process is not running, the command will return nothing.

You can also use systemctl command to check whether a service is running or not.

systemctl status nginx

This command will show the status of the service and it will be active (running) or inactive (dead)

You can also check the return code of the command, it will be 0 if process is running and non-zero if the process is not running.

pgrep nginx || echo "Process not running"

or

if pgrep nginx > /dev/null; then echo "Process is running"; else echo "Process is not running"; fi

These are some examples of how you can check if a process is running or not on Linux/Unix using the command-line.

Leave a Comment