我需要检查输入参数的存在。我有以下脚本

if [ "$1" -gt "-1" ]
  then echo hi
fi

我明白了

[: : integer expression expected

如何首先检查输入参数1以查看它是否存在?


当前回答

最好这样演示

if [[ $# -eq 0 ]] ; then
    echo 'some message'
    exit 1
fi

如果参数太少,通常需要退出。

其他回答

它是:

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi

$#变量将告诉您脚本传递的输入参数的数量。

或者,您可以检查参数是否为空字符串或类似于:

if [ -z "$1" ]
  then
    echo "No argument supplied"
fi

z开关将测试“$1”的扩展是否为空字符串。如果它是空字符串,则执行主体。

另一种检测参数是否传递给脚本的方法:

((!$#)) && echo No arguments supplied!

注意((expr))会导致表达式按照Shell算术的规则进行求值。

为了在没有任何争论的情况下退出,可以说:

((!$#)) && echo No arguments supplied! && exit 1

另一种(类似的)方式是:

let $# || echo No arguments supplied

let $# || { echo No arguments supplied; exit 1; }  # Exit if no arguments!

help let表示:

let:let arg[arg…]计算算术表达式。...退出状态:如果最后一个ARG的值为0,则返回1;否则,let返回0。

如果要检查参数是否存在,可以检查参数的#是否大于或等于目标参数编号。

下面的脚本演示了这是如何工作的

测试.sh

#!/usr/bin/env bash

if [ $# -ge 3 ]
then
  echo script has at least 3 arguments
fi

产生以下输出

$ ./test.sh
~
$ ./test.sh 1
~
$ ./test.sh 1 2
~
$ ./test.sh 1 2 3
script has at least 3 arguments
$ ./test.sh 1 2 3 4
script has at least 3 arguments

Try:

 #!/bin/bash
 if [ "$#" -eq  "0" ]
   then
     echo "No arguments supplied"
 else
     echo "Hello world"
 fi

更现代

#!/usr/bin/env bash

if [[ $# -gt 0 ]]
  then echo Arguments were provided.
  else echo No arguments were provided.
fi