-1

I'm trying to use if-condition in my shell script and have been facing the following issue:

status=$echo ps -ef | grep mysql | cut -c10-15 #--> It produces process-id (for e.g. 012345), if exits, or else returns null

echo $status #--> This prints the process id correctly (for e.g. 012345), but it doesn't take value in if condition

if [ -z "$status" ] #--> it should not be NULL as the variable here is 012345  
then
    echo "Need to start server"
else
    echo "Server already up and running"
fi

Prints first case even if the "status" variable not NULL.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

1

echo $status isn't outputting the process id; the previous ps command is.

You didn't use a command substitution, so you ran the command ps with status set to the empty string in its environment. When you do run echo $status, you just get a blank line, since status isn't set.

The code should be

status=$(ps -ef | grep mysql | cut -c10-15)
if [ -z "$status" ]; then
  echo "Need to start server"
else
  echo "Server already up and running"
fi
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks for the reply. I did follow what you told me to do. Doing this too, I'm getting the empty string in variable STATUS. I used `set -x` to debug, it shows `status= ' [ ' -z ' ' ' ] ' ` and fails the if condition. More help is appreciated. I'm fairly new in this shell scripting. – Siddharth Gandhi Apr 06 '20 at 19:54