0

I am having a really a hard time to evaluate conditional strings and numbers. After hours of reading and trying with (my Beginners Guide) I keep getting the error msgs like syntax error in conditional expression, unary operator expected, conditional binary operator expected etc..

Something is wrong inside the if-condition - but I don't get it. I tried with arithmetic operators -ge, -le but that didn't work either. Please, no worries about the debatable logic of this code-snip.

Working with Raspbian (Debian) on my Raspberry.

#!/bin/sh
NAME=syslogd
PID=/var/run/$NAME.pid
PIDofP=`pidof $NAME`
 if [[ $PIDofP = "" ]] #empty, at least not visible 
 then
 echo " No process is running."
 fi
 if [[ $PIDofP < 1000 ]]
 then
 echo " The PID-number is lower than 1000. ($PID: $PIDofP)"
 fi
 if [[ "$PIDofP" > 999 ]]
 then
 echo " The PID-number is higher than 1000. ($PID: $PIDofP)"
 fi 
exit 0

Is there a way to evaluate a string, number, integer or whatever to learn what kind it is? Say I just have a bunch of numbers and/or letters and want to know about the 'format' they are held in - to be used afterwards, hopefully without spending hours finding the proper syntax.

Sorry, first time writing bash.script

Pierre.Vriens
1,08621 gold badges13 silver badges16 bronze badges
asked Dec 13, 2015 at 12:56
2
  • What do you want the script to do? Is your problem that you get both the "No process named: $NAME is running" message and the "The PID-number is lower than 1000." when the PID is blank? Commented Dec 13, 2015 at 16:27
  • Basically I want to compare real number values instead of 'lexical' values and yes, the return of pidofmay be blank. Correct: $NAME will throw an error (edited question). Commented Dec 13, 2015 at 16:36

1 Answer 1

1

The unary operator expected error was likely due to $PIDofP not being in quotes in the conditional. In that case when $PIDofP is an empty string the shell sees no value at all on the left side of = instead of a blank value, hence the error message.

The following snippet implements the PID comparison logic correctly through the use of if/elif/else, which guarantees only one of the three possible echo outputs is generated. It uses the POSIX comparison syntax (see What is the difference between double and single square brackets in bash?).

#!/bin/sh
NAME=syslogd
PID=/var/run/$NAME.pid
PIDofP=`pidof $NAME`
if [ "$PIDofP" = "" ]; then
 echo " No process is running."
elif [ "$PIDofP" -lt 1000 ]; then
 echo " The PID number is lower than 1000. ($PID: $PIDofP)"
else
 # $PIDofP is >= 1000.
 echo " The PID number is 1000 or higher. ($PID: $PIDofP)"
fi
exit 0
answered Dec 13, 2015 at 17:12
1
  • Thank you! Also for that link. Will have to study all that. Happy Holidays. Commented Dec 13, 2015 at 19:12

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.