If condition help required

I have a if condition it checks its pid exist it means it is running, otherwise not running.

I am checking with ps


x=`ps -fu myuserid|grep java| |grep -v grep | awk '{print $2}'`

if [$x -eq 0 ]

then ............

Above code is giving integer error, because currently process of java is not running so its value is zero, so how i can i do that to check process exist then tell us process exist, otherwise tell us process not exist.

If should have space between brackets...
can reduce one grep
and avoid use of back tick's

try

x=$(ps -fu myuserid| grep -v grep | awk '/java/{print $2}')

if [ $x -eq 0 ]
1 Like
x=$(ps -fu myuserid | grep [j]ava | awk '{print $2}')
if [ ! -z $x ]
then
  echo process is running
else
  echo process not running
fi
1 Like
if [ $(ps -fu myuserid | grep -c [j]ava) -gt 0 ]
then    echo 'process is running'
else    echo 'process not running'
fi
2 Likes

Or:

ps -fu myuserid | grep [j]ava > /dev/null &&
  echo 'process is running' ||
    echo 'process not running'
if ps -fu myuserid | grep [j]ava > /dev/null; then
  echo 'process is running' 
else  
  echo 'process not running'
fi

If the grep implementation supports -q you can get rid of the > /dev/null part.
If pgrep is available (Linux/Solaris) you could substitute the above ps .. | grep .. pipeline with: pgrep -u myuserid -f [j]ava

1 Like