如何测试 BASH 中是否提供了参数并且小于 2?

How to test if arguments were supplied and are less than 2 in BASH?

我正在创建一个脚本,其中用户必须提供第一个参数是必需的,第二个参数是可选的。如果它小于 1 个或大于 2 个参数,应该抛出错误。

这是我目前所做的:

if [ $# -eq 0 -o $# -gt 2]
  then
    echo " *** ! No arguments were supplied. *** !"

    echo " Usage example is: sudo myserver pathToYourFolder [URL]"
    echo ""
    echo " The first argument 'pathToYourFolder' is mandatory. 
           It is the path to your mysite folder. 
           Please use like this example: sudo myserver /Users/jhon/Documents/mysite"
    echo ""
    echo " The second argument 'URL' is optional. It shuld be the desired URL to run with the server in Docker. 
           If not provided the default will be 'my-dev.com'.    
           If you want to set yours, please use llike this example: my-url.com. 
           Please note: It will be recorded in your /etc/hosts."
    echo ""
  else       
    if [  -eq 0 ]      
      then
        FULLPATH="/Users/jhon/Documents/mysite"
      else
        FULLPATH=""
    fi

    if [  -eq 0 ]        
      then       
        DOMAIN="my-dev.com"
      else
        DOMAIN=""
    fi

    echo ""
    echo "Sit path to $FULLPATH"
    echo ""
    echo "HTTP_PORT to $HTTP_PORT"
    echo ""
    echo "Sit domain to $DOMAIN"
    echo ""

    if ! grep -lq $DOMAIN /etc/hosts;
      then    
        echo "127.0.0.1       $DOMAIN" >> /etc/hosts
        echo "$DOMAIN saved in /etc/hosts"
        else
        echo "$DOMAIN already in /etc/hosts"  
    fi
    echo ""
    echo ""

    docker run -p 80:80  -v $FULLPATH:/var/www/html myorg/srv_php56:v001

fi

问题出在第一个条件 if [ $# -eq 0 -o $# -gt 2] 中。条件是如果参数为零或大于 2 则抛出错误。

我收到的错误信息是

./myserver.sh: line 32: [: missing `]'
./myserver.sh: line 50: [: -eq: unary operator expected
./myserver.sh: line 58: [: -eq: unary operator expected

我做错了什么?

去这里拿一个space:

if [ $# -eq 0 -o $# -gt 2 ]
                         ^

Bash 用白色 space 分隔参数,特别是 space 和制表符。如果写成2].

,它将被视为单个参数