bash 如何检查是否存在第二个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34117825/
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-18 14:00:36  来源:igfitidea点击:

How to check for the existence of a second argument

bash

提问by cade galt

I need to update this bash function I use for doing things with git:

我需要更新我用来处理 git 的这个 bash 函数:

push() {
  a=
  if [ $# -eq 0 ]
    then
      a=$(timestamp)
  fi
  # ... do stuff
}

but I don't know how this line works

但我不知道这条线是如何运作的

 if [ $# -eq 0 ]

I need to check for a first argument and then I need to check for a second argument.

我需要检查第一个参数,然后我需要检查第二个参数。

So there will be 2 if statements.

所以会有2个if语句。

How can I update this and how does this line work

我怎样才能更新这个以及这条线是如何工作的

 if [ $# -eq 0 ]

采纳答案by joranvar

You could create a small script to look into how $#changes when you call the function with different numbers of arguments. For instance:

您可以创建一个小脚本来查看$#当您使用不同数量的参数调用函数时会发生什么变化。例如:

[Contents of "push.sh":]

[“push.sh”的内容:]

push() {
    echo $#
}

echo "First call, no arguments:"
push
echo "Second call, one argument:"
push "First argument"
echo "Third call, two arguments:"
push "First argument" "And another one"

If you put this in a script and run it, you'll see something like:

如果你把它放在一个脚本中并运行它,你会看到类似的东西:

-> % ./push.sh
First call, no arguments:
0
Second call, one argument:
1
Third call, two arguments:
2

This tells you that the value of $#contains the number of arguments given to the function.

这告诉您 的值$#包含提供给函数的参数数量。

The if [ $# -eq 0 ]part you can add to the script, and change the 0 to some other numbers to see what happens. Also, an internet search for "bash if" will reveal the meaning of the -eqpart, and show that you could also use -ltor -gt, for instance, testing whether a number is less than or greater than another.

if [ $# -eq 0 ]部分可以添加到脚本,将0改为其他一些数字来看看会发生什么。此外,在互联网上搜索“ bash if”将揭示该-eq部分的含义,并表明您还可以使用-ltor -gt,例如,测试一个数字是小于还是大于另一个。

In the end, you'll likely want to use something like the following:

最后,您可能希望使用以下内容:

a=
b=

if [ $# -lt 1 ]
then
   a=$(timestamp)
fi

if [ $# -lt 2 ]
then
    b=$(second thing)
fi

回答by Lix

The $#part is a variable that contains the number of arguments passed to the script.

$#部分是一个变量,包含传递给脚本的参数数量。

The conditional statement there checks the value of that variable using -eqand it's checking if the value is zero (as in no arguments were passed).

那里的条件语句使用检查该变量的值,-eq并检查该值是否为零(因为没有传递参数)。

In order to check for two arguments, you can change (or add) that line to read like this:

为了检查两个参数,您可以更改(或添加)该行,如下所示:

 if [ $# -eq 2 ]