samedi 30 mai 2015

IF operations on variables

I'm building a script in bash for use on Linux (SLES 11SP3). I'd like to check whether a certain process exists by looking up it's pid using this syntax:

pid="$(ps -ef | grep -v grep | grep /sbin/syslog-ng | awk '{print $2}')"

This fills variable pid with the pid of the syslog-ng process. Then I want to use this variable in an if statement:

if [ ${pid} > 0 ]; then
  do something
else
  do something else
fi

The problem is that this if statement seems to always be false, even if the variable pid has a value higher than 0. So, the else part is always executed instead of the correct (if condition is true) statement.

I had a similar issue with the use of wc -l to check the existence of filesystems:

exist_tmp=$(df -x fuse.gvfs-fuse-daemon -h | grep /tmp | wc -l)
if [ ${exist_tmp} > 0 ]; then
  do something
fi

This would not work, even if the variable has a value of 1, indicating the existence of a /tmp filesystem. It started working (or at least doing what I wanted it to do), when I changed the syntax to this:

if [ ${exist_tmp} != 0 ]; then
  do something
fi

The difference between greater than 0 and not equal to 0 eludes me a bit in this used case.

The questions therefor are:

  1. Does anybody have an idea why the pid lookup and if statement won't do what I want it to do?
  2. Does anybody have an idea what the problem with the > 0 and != 0 might have been?

Any input is greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire