batuhan kırçova
batuhan kırçova

Reputation: 25

Linux Bash Script Ps result is NOT Expected

I have a script like that :

#!/bin/bash

RETVAL=$(ps -ef|  grep -v color | grep opscenter)

echo $RETVAL


if [ "$RETVAL" = "" ];
then
    echo 'Opscenter is NOT running.'
    ./root/opscenter_install/opscenter-6.8.16/bin/opscenter
else
    echo 'Opscenter is running'
    exit 1
fi


exit 0

When I run this command on OS , the result is empty :

ps -ef| grep -v color | grep opscenter

When I run this sh , the retval result is like that :

root 27834 24318 0 12:47 pts/1 00:00:00 sh opscentercheck.sh root 27835 27834 0 12:47 pts/1 00:00:00 sh opscentercheck.sh root 27838 27835 0 12:47 pts/1 00:00:00 grep opscenter

How could I solve this problem ?

Thank you

Result should be Opscenter is NOT running.

Thank you.

Upvotes: 0

Views: 95

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

You're probably using grep -v color because you have an alias like alias grep='grep --color=auto'. When you're running a script, your aliases are not present. You could

  • use grep -v grep
  • use ps -ef | grep '[o]pscenter' which makes the pattern not match the string so the "grep" command will not be matched.

Now, avoiding the script matching:

  • use ps -ef | grep '[o]pscenter | grep -Fv 'opscenter.sh' to filter out the script
  • use pgrep opscenter which searches for the process matching "opscenter", not the full command line. This would not match "sh opscenter.sh" because "sh" does not match the pattern "opscenter"

Upvotes: 3

Related Questions