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

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

我明白了

[: : integer expression expected

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


当前回答

单行bash函数验证

myFunction() {

    : ${1?"forgot to supply an argument"}
    if [ "$1" -gt "-1" ]; then
        echo hi
    fi

}

添加函数名称和用法

myFunction() {

    : ${1?"forgot to supply an argument ${FUNCNAME[0]}() Usage:  ${FUNCNAME[0]} some_integer"}
    if [ "$1" -gt "-1" ]; then
        echo hi
    fi

}

添加验证以检查整数

要添加其他验证,例如检查传递的参数是否为整数,请修改验证一行以调用验证函数:

: ${1?"forgot to supply an argument ${FUNCNAME[0]}() Usage:  ${FUNCNAME[0]} some_integer"} && validateIntegers $1 || die "Must supply an integer!"

然后,构造一个验证函数来验证参数,成功时返回0,失败时返回1,失败时终止脚本

validateIntegers() {

    if ! [[ "$1" =~ ^[0-9]+$ ]]; then
        return 1 # failure
    fi
    return 0 #success

}

die() { echo "$*" 1>&2 ; exit 1; }

更简单-只需使用set-u

set-u确保每个被引用的变量在使用时都被设置,所以只需设置它就可以了

myFunction() {
    set -u
    if [ "$1" -gt "-1" ]; then
        echo hi
    fi

}

其他回答

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

((!$#)) && 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

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

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

Try:

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

我经常将这段代码用于简单的脚本:

#!/bin/bash

if [ -z "$1" ]; then
    echo -e "\nPlease call '$0 <argument>' to run this command!\n"
    exit 1
fi