检查 Bash shell 脚本中输入参数的存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6482377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:42:29  来源:igfitidea点击:

Check existence of input argument in a Bash shell script

bashshell

提问by user775187

I need to check the existence of an input argument. I have the following script

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

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

I get

我得到

[: : integer expression expected

How do I check the input argument1 first to see if it exists?

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

回答by phoxis

It is:

这是:

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

The $#variable will tell you the number of input arguments the script was passed.

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

Or you can check if an argument is an empty string or not like:

或者,您可以检查参数是否为空字符串,例如:

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

The -zswitch will test if the expansion of "$1" is a null string or not. If it is a null string then the body is executed.

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

回答by Val

It is better to demonstrate this way

最好以这种方式演示

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

You normally need to exit if you have too few arguments.

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

回答by Aleks N.

In some cases you need to check whether the user passed an argument to the script and if not, fall back to a default value. Like in the script below:

在某些情况下,您需要检查用户是否向脚本传递了参数,如果没有,则回退到默认值。就像下面的脚本:

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

Here if the user hasn't passed scaleas a 2nd parameter, I launch Android emulator with -scale 1by default. ${varname:-word}is an expansion operator. There are other expansion operators as well:

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

  • ${varname:=word}which setsthe undefined varnameinstead of returning the wordvalue;
  • ${varname:?message}which either returns varnameif it's defined and is not null or prints the messageand aborts the script (like the first example);
  • ${varname:+word}which returns wordonly if varnameis defined and is not null; returns null otherwise.
  • ${varname:=word}其中设置了未定义varname而不是返回的word值;
  • ${varname:?message}varname如果它已定义并且不为空,则返回或打印message并中止脚本(如第一个示例);
  • ${varname:+word}word仅当varname已定义且不为空时才返回;否则返回 null。

回答by Ranjithkumar T

Try:

尝试:

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

回答by devnull

Another way to detect if arguments were passed to the script:

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

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

Note that (( expr ))causes the expression to be evaluated as per rules of Shell Arithmetic.

请注意,这(( expr ))会导致表达式按照Shell Arithmetic 的规则进行计算

In order to exit in the absence of any arguments, one can say:

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

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


Another (analogous)way to say the above would be:

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

let $# || echo No arguments supplied

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

help letsays:

help let说:

let: let arg [arg ...]

  Evaluate arithmetic expressions.

  ...

  Exit Status:
  If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.

let: let arg [arg ...]

  Evaluate arithmetic expressions.

  ...

  Exit Status:
  If the last ARG evaluates to 0, let returns 1; let returns 0 otherwise.

回答by f2cx

I often use this snippet for simple scripts:

我经常将这个片段用于简单的脚本:

#!/bin/bash

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

回答by seorphates

Only because there's a more base point to point out I'll add that you can simply test your string is null:

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

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

Likewise if you're expecting arg count just test your last:

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

#!/usr/bin/env bash

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

and so on with any arg or var

等等任何 arg 或 var

回答by Brad Parks

If you'd like to check if the argument exists, you can check if the # of arguments is greater than or equal to your target argument number.

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

The following script demonstrates how this works

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

test.sh

测试文件

$ ./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

produces the following output

产生以下输出

var=$(( var + 0 ))

回答by Cwissy

As a small reminder, the numeric test operators in Bash only work on integers (-eq, -lt, -ge, etc.)

作为一个小提醒,数字测试运营商猛砸只在整数的工作(-eq-lt-ge等)

I like to ensure my $vars are ints by

我喜欢通过以下方式确保我的 $vars 是整数

myFunction() {

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

}

before I test them, just to defend against the "[: integer arg required" error.

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

回答by AndrewD

one liner bash function validation

一个班轮bash函数验证

myFunction() {

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

}

add function name and usage

添加函数名称和用法

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

add validation to check if integer

添加验证以检查是否为整数

to add additional validation, for example to check to see if the argument passed is an integer, modify the validation one liner to call a validation function:

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

validateIntegers() {

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

}

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

then, construct a validation function that validates the argument, returning 0 on success, 1 on failure and a die function that aborts script on failure

然后,构造一个验证参数的验证函数,成功时返回 0,失败时返回 1,以及一个在失败时中止脚本的 die 函数

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

}

Even simpler - just use set -u

更简单 - 只需使用 set -u

set -umakes sure that every referenced variable is set when its used, so just set it and forget it

set -u确保在使用时设置每个引用的变量,因此只需设置它并忘记它

##代码##