Different in typing command and using shell script

Wondering why belows code works fine if i type in the command prompt but it seems not executed when i code them in a file with additional if-then-else statement.

#!/bin/sh

. $HOME/.profile

pid=`ps -ef | grep -w XELstnr | grep -v grep | awk {'print $2'}`

if [ $pid !='' ]
then
  echo "Stopping XELstnr....."
  kill -9 $pid
  echo "XELstnr stopped."
else
  echo "XELstnr is not running."

fi

exit

Please advise. Thanks.

The if-else construct should be

if [ ! -z $pid ]

rather than

if [ $pid != ' ' ]

Vino, $pid must be between quotes :

if [ ! -z "$pid" ]

or

if [ -n "$pid" ]

Jean-Pierre.