Citizen SP
Citizen SP

Reputation: 1411

Bash script to check multiple running processes

I'm made the following code to determine if a process is running:

#!/bin/bash
ps cax | grep 'Nginx' > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

I would like to use my code to check multiple processes and use a list as input (see below), but getting stuck in the foreach loop.

CHECK_PROCESS=nginx, mysql, etc

What is the correct way to use a foreach loop to check multiple processes?

Upvotes: 0

Views: 13569

Answers (3)

dimir
dimir

Reputation: 793

Create file chkproc.sh

#!/bin/bash

for name in $@; do
    echo -n "$name: "
    pgrep $name > /dev/null && echo "running" || echo "not running"
done

And then run:

$ ./chkproc.sh nginx mysql etc
nginx: not running
mysql: running
etc: not running

Unless you have some old or "weird" system you should have pgrep available.

Upvotes: 1

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

If your system has pgrep installed, you'd better use it instead of the greping of the output of ps.

Regarding you're question, how to loop through a list of processes, you'd better use an array. A working example might be something along these lines:

(Remark: avoid capitalized variables, this is an awfully bad bash practice):

#!/bin/bash

# Define an array of processes to be checked.
# If properly quoted, these may contain spaces
check_process=( "nginx" "mysql" "etc" )

for p in "${check_process[@]}"; do
    if pgrep "$p" > /dev/null; then
        echo "Process \`$p' is running"
    else
        echo "Process \`$p' is not running"
    fi
done

Cheers!

Upvotes: 4

P.P
P.P

Reputation: 121387

Use a separated list of of processes:

#!/bin/bash
PROC="nginx mysql ..."
for p in $PROC
do
  ps cax | grep $p > /dev/null

  if [ $? -eq 0 ]; then
    echo "Process $p is running."
  else
    echo "Process $p is not running."
  fi

done

If you simply want to see if either one of them is running, then you don't need loo. Just give the list to grep:

ps cax | grep -E "Nginx|mysql|etc" > /dev/null

Upvotes: 2

Related Questions