Bash脚本 获取提供的命令行参数数量

Bash内部变量$#保存了命令行参数的总数:

#!/bin/bash
echo $#

将上面内容保存到脚本arguments.sh中,并执行:

$bash arguments.sh 1 2 3 4
4

有时在编写脚本时,我们需要强制要求用户提供正确数量的参数。
那么可以这样实现:

#!/bin/bash
if [ "$#" -ne 2 ]; then
    echo "必须提供两个命令行参数"
fi
echo $#

如果参数的数量不等于2,则上述脚本将退出。

$bash arguments.sh 1 
必须提供两个命令行参数
$bash arguments.sh 1 2 3 4
必须提供两个命令行参数
$bash arguments.sh 1 2
2
日期:2020-07-07 20:54:29 来源:oir作者:oir