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
1 Answer 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
-
Thank you! Also for that link. Will have to study all that. Happy Holidays.snahl– snahl2015年12月13日 19:12:50 +00:00Commented Dec 13, 2015 at 19:12
pidof
may be blank. Correct: $NAME will throw an error (edited question).