检查bash脚本中是否至少提供了两个参数

时间:2021-07-07 00:15:35

I am trying to write a script that mimics cp where there is a source and destination input. how can I count the number of arguments given on the command line

我正在尝试编写一个模拟cp的脚本,其中有源和目标输入。如何计算命令行中给出的参数数量

for example

例如

./myscript src dest

./myscript src dest

check that at least 2 things were given.

检查至少有2件事。

2 个解决方案

#1


25  

Use the $# special variable. Its value is the number of arguments. So if you have a script that contains only:

使用$#特殊变量。它的值是参数的数量。因此,如果您的脚本仅包含:

echo $#

and execute it like this:

并执行它:

thatscript foo bar baz quux

It'll print 4.

它会打印4。

In your case you may want to do something like:

在您的情况下,您可能想要做以下事情:

if [ $# -ne 2 ]; then
    # TODO: print usage
    exit 1
fi

#2


16  

Going by the requirement from the question that the arguments should contain "at least 2 things", I think it might be more accurate to check:

根据参数应该包含“至少2件事”的问题的要求,我认为检查可能更准确:

if (( $# < 2 )); then
    # TODO: print usage
    exit 1
fi

Using arithmetic expansion (( )) will prevent this from hitting exit 1 for any value not equal to 2.

使用算术扩展(())将阻止此命令出现任何不等于2的值。

If you use if [ $# -ne 2 ]; it will trigger the conditional for any number of arguments other than 2.

如果你使用if [$#-ne 2];它将触发除2之外的任何数量的参数的条件。

#1


25  

Use the $# special variable. Its value is the number of arguments. So if you have a script that contains only:

使用$#特殊变量。它的值是参数的数量。因此,如果您的脚本仅包含:

echo $#

and execute it like this:

并执行它:

thatscript foo bar baz quux

It'll print 4.

它会打印4。

In your case you may want to do something like:

在您的情况下,您可能想要做以下事情:

if [ $# -ne 2 ]; then
    # TODO: print usage
    exit 1
fi

#2


16  

Going by the requirement from the question that the arguments should contain "at least 2 things", I think it might be more accurate to check:

根据参数应该包含“至少2件事”的问题的要求,我认为检查可能更准确:

if (( $# < 2 )); then
    # TODO: print usage
    exit 1
fi

Using arithmetic expansion (( )) will prevent this from hitting exit 1 for any value not equal to 2.

使用算术扩展(())将阻止此命令出现任何不等于2的值。

If you use if [ $# -ne 2 ]; it will trigger the conditional for any number of arguments other than 2.

如果你使用if [$#-ne 2];它将触发除2之外的任何数量的参数的条件。