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

时间:2017-11-22 15:28:05

标签: bash comparator

我正在创建一个脚本,用户必须提供必需的第一个参数,第二个参数是可选的。如果小于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 [ $1 -eq 0 ]      
      then
        FULLPATH="/Users/jhon/Documents/mysite"
      else
        FULLPATH="$1"
    fi

    if [ $2 -eq 0 ]        
      then       
        DOMAIN="my-dev.com"
      else
        DOMAIN="$2"
    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

我做错了什么?

1 个答案:

答案 0 :(得分:4)

在这里获得一个空间:

2]

Bash按空格分隔参数,特别是空格和制表符。如果写成import { MatInputModule, MatCheckboxModule, MatRadioModule } from '@angular/material'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; TestBed.configureTestingModule({ declarations: [ EventFormComponent ], imports: [ TranslateModule.forRoot(), ReactiveFormsModule, NoopAnimationsModule, MatInputModule, MatCheckboxModule, MatRadioModule ], providers: [ FormBuilder ] }).compileComponents(); ,它将被视为单个参数。