Help to prepare script for monitor services

I need to monitor services in rhel 8
below are the service......
crond
chronyd
rsyslogd
sshd
sssd
firewalld

Scripts..........

#!/bin/bash
for i in "${SERVICES[@]}"
do
###CHECK SERVICE####
`pgrep $i `
STATS=(echo $?)

if [  $STATS == 0  ]
then
echo   "$i is running"
else
echo   "$i is not running"
fi
done

but after run script, output does not come. please help, where is the problem in scripts.

--- Post updated at 07:17 PM ---

I prepared another script. but getting error.

#!/bin/bash
for i in `cat SERVICES`
do
###CHECK SERVICE####
status=systemctl | grep running |grep $i |awk '{print $4}'
if [ $status -eq running ]
then
     echo "$i is running"
else
     echo "$i is not running"
fi
done

Output-

[root@localhost ~]# sh service1.sh
service1.sh: line 6: [: -eq: unary operator expected
crond is not running
service1.sh: line 6: [: -eq: unary operator expected
chronyd is not running
service1.sh: line 6: [: -eq: unary operator expected
rsyslogd is not running
service1.sh: line 6: [: -eq: unary operator expected
sshd is not running
service1.sh: line 6: [: -eq: unary operator expected
sssd is not running
service1.sh: line 6: [: -eq: unary operator expected
firewalld is not running

Why it is coming error.

In your first script, you're both too generous, and not enough, with "command substitutions". Try

for i in "${SERVICES[@]}"
  do    pgrep $i >/dev/null
        STATS=$?
        if [  $STATS == 0  ]
          then  echo   "$i is running"
          else  echo   "$i is not running"
        fi
  done
crond is not running
chronyd is not running
rsyslogd is running
sshd is not running
sssd is not running
firewalld is not running
 

You could reduce that to

for i in "${SERVICES[@]}"
  do    if pgrep $i >/dev/null
          then  echo   "$i is running"
          else  echo   "$i is not running"
        fi
  done

EDIT: or even

for i in "${SERVICES[@]}"
  do    echo "$i is $(pgrep $i >/dev/null || echo not\ )running"
  done

EDIT 2: pertaining to your second script, -eq compares integer values, not strings. Use = .
EDIT 3: in case you can drop the non-running services print out, try taking advantage of pgrep 's pattern evaluation capability for a single command line:

printf "%0.0s%s is running.\n" $(IFS=\|; pgrep -l "${SERVICES
[*]}")
rsyslogd is running.
firefox is running.
1 Like