Search code examples
shellshunary-operator

Getting "unary operator expected" in my sh script


I’m trying to write a startup script for my service using sh but having trouble with the following line

#!/bin/sh
…
if [ `ps --pid $ppid 2> /dev/null | grep -c $ppid 2> /dev/null` -eq '1' ]; then

I get the error

Starting jboss-as: /etc/init.d/jboss: line 106: [: -eq: unary operator expected

I can’t tell what is wrong with the eq conditional. Any advice? - Dave


Solution

  • The only way I could reproduce your error is when the ppid variable is empty.

    #! /bin/sh
    
    ppid=''
    
    
    if [ `ps --pid $ppid 2> /dev/null | grep -c $ppid 2> /dev/null` -eq '1' ]; then
        echo running;
    else
        echo not running;
    fi
    

    You can check for variable emptyness using

    if [ -z "$ppid" ]; then 
      echo "ppid is empty;"
    fi
    

    EDIT: Combining both:

    #! /bin/sh
    
    ppid=
    
    
    if [[ ! -z "$ppid" && $(ps --pid $ppid 2> /dev/null | grep -c $ppid 2> /dev/null) -eq '1' ]]; then
        echo running;
    else
        echo not running or pid null;
    fi
    

    LAST EDIT: Actually your problem comes from not quoting variable expansion:

    #! /bin/sh
    
    ppid=
    
    
    if [ $(ps --pid "$ppid" 2> /dev/null | grep -c "$ppid" 2> /dev/null) -eq '1' ]; then
        echo running;
    else
        echo not running or pid null;
    fi
    

    See #5: http://fahdshariff.blogspot.co.uk/2013/10/shell-scripting-best-practices.html#BP5