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

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

我明白了

[: : integer expression expected

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


当前回答

在某些情况下,您需要检查用户是否向脚本传递了参数,如果没有,则返回默认值。如以下脚本所示:

scale=${2:-1}
emulator @$1 -scale $scale

在这里,如果用户没有通过scale作为第二个参数,我默认使用scale 1启动Android模拟器${varname:-word}是一个扩展运算符。还有其他扩展运营商:

${varname:=word},它设置未定义的varname而不是返回word值;${varname:?message},如果已定义且不为空,则返回varname,或者打印消息并中止脚本(如第一个示例);${varname:+word},仅当varname已定义且不为空时才返回word;否则返回null。

其他回答

最好这样演示

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

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

Try:

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

单行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

}

只是因为有更多的基点需要指出,所以我补充说,您可以简单地测试字符串是否为空:

if [ "$1" ]; then
  echo yes
else
  echo no
fi

同样,如果您期望arg计数,只需测试最后一个:

if [ "$3" ]; then
  echo has args correct or not
else
  echo fixme
fi

以此类推,使用任何arg或var

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

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

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