Bash script error [: !=: unary operator expected

后端 未结 2 1133
你的背包
你的背包 2020-11-27 03:58

In my script I am trying to error check if the first and only argument is equal to -v but it is an optional argument. I use an if statement but I keep getting the unary oper

相关标签:
2条回答
  • 2020-11-27 04:11

    Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

    In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

    #!/bin/sh
    case $1 in
      '-v') if [ "$1" = -v ]; then
             echo "`ps -ef | grep -v '\['`"
            else
             echo "`ps -ef | grep '\[' | grep root`"
            fi;;
         *) echo "usage: $0 [-v]"
            exit 1;; #It is good practice to throw a code, hence allowing $? check
    esac
    

    If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

    #!/bin/sh
    
    usage ()
     {
      echo "usage: $0 [-v]"
      exit 1
     }
    
    unset arg_match
    
    for arg in $*
     do
      case $arg in
        '-v') if [ "$arg" = -v ]; then
               echo "`ps -ef | grep -v '\['`"
              else
               echo "`ps -ef | grep '\[' | grep root`"
              fi
              arg_match=1;; # this is set, but could increment.
           *) ;;
      esac
    done
    
    if [ ! $arg_match ]
     then
      usage
    fi
    

    But, allow multiple occurrences of an argument is convenient to use in situations such as:

    $ adduser -u:sam -s -f -u:bob -trace -verbose
    

    We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

    $ adduser -u sam -s -f -u bob -trace -verbose
    
    0 讨论(0)
  • 2020-11-27 04:28

    Quotes!

    if [ "$1" != -v ]; then
    

    Otherwise, when $1 is completely empty, your test becomes:

    [ != -v ]
    

    instead of

    [ "" != -v ]
    

    ...and != is not a unary operator (that is, one capable of taking only a single argument).

    0 讨论(0)
提交回复
热议问题