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

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

我明白了

[: : integer expression expected

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


当前回答

最好这样演示

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

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

其他回答

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

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

测试.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

在我的情况下(有7个参数),唯一有效的解决方案是检查最后一个参数是否存在:

if [[ "$7" == '' ]] ; then
  echo "error"
  exit
fi

Try:

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

最好这样演示

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

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

作为一个小提示,Bash中的数字测试运算符只对整数(-eq、-lt、-ge等)有效

我希望通过以下方式确保我的$vars为int

var=$(( var + 0 ))

在我测试它们之前,只是为了防御“[:integer arg required”错误。