0

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?

Citizen SP
  • 1,411
  • 7
  • 36
  • 68

3 Answers3

4

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!

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
2

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
P.P
  • 117,907
  • 20
  • 175
  • 238
1

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.

dimir
  • 693
  • 6
  • 23