检查传递给Bash脚本的参数数量

本文翻译自:Check number of arguments passed to a Bash script

I would like my Bash script to print an error message if the required argument count is not met. 如果不满足所需的参数计数,我希望我的Bash脚本能够打印错误消息。

I tried the following code: 我尝试了以下代码:

#!/bin/bash
echo Script name: $0
echo $# arguments 
if [$# -ne 1]; 
    then echo "illegal number of parameters"
fi

For some unknown reason I've got the following error: 由于某些未知原因,我遇到以下错误:

test: line 4: [2: command not found

What am I doing wrong? 我究竟做错了什么?


#1楼

参考:https://stackoom.com/question/1FuZG/检查传递给Bash脚本的参数数量


#2楼

Just like any other simple command, [ ... ] or test requires spaces between its arguments. 就像任何其他简单命令一样, [ ... ]test需要在其参数之间留出空格。

if [ "$#" -ne 1 ]; then
    echo "Illegal number of parameters"
fi

Or 要么

if test "$#" -ne 1; then
    echo "Illegal number of parameters"
fi

Suggestions 建议

When in Bash, prefer using [[ ]] instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression. 在Bash中,更喜欢使用[[ ]]因为它不会对其变量执行分词和路径名扩展,除非它是表达式的一部分,否则引用可能不是必需的。

[[ $# -ne 1 ]]

It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with extglob ) and regex matching. 它还有一些其他功能,如不带引号的条件分组,模式匹配(与extglob扩展模式匹配)和正则表达式匹配。

The following example checks if arguments are valid. 以下示例检查参数是否有效。 It allows a single argument or two. 它允许一个或两个参数。

[[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]]

For pure arithmetic expressions, using (( )) to some may still be better, but they are still possible in [[ ]] with its arithmetic operators like -eq , -ne , -lt , -le , -gt , or -ge by placing the expression as a single string argument: 对于纯算术表达式,使用(( ))可能仍然会更好,但它们仍然可以在[[ ]]使用其算术运算符,如-eq-ne-lt-le-gt-ge将表达式放在单个字符串参数中:

A=1
[[ 'A + 1' -eq 2 ]] && echo true  ## Prints true.

That should be helpful if you would need to combine it with other features of [[ ]] as well. 如果您需要将它与[[ ]]其他功能结合使用,这应该会有所帮助。

Exiting the script 退出脚本

It's also logical to make the script exit when invalid parameters are passed to it. 当无效参数传递给脚本时,使脚本退出也是合乎逻辑的。 This has already been suggested in the comments by ekangas but someone edited this answer to have it with -1 as the returned value, so I might as well do it right. 这已经在ekangas评论中提出过,但有人编辑了这个答案,以-1作为返回值,所以我不妨正确地做到这一点。

-1 though accepted by Bash as an argument to exit is not explicitly documented and is not right to be used as a common suggestion. -1虽然被Bash接受作为exit的参数没有明确记录,并且不适合用作常见建议。 64 is also the most formal value since it's defined in sysexits.h with #define EX_USAGE 64 /* command line usage error */ . 64也是最正式的值,因为它在sysexits.h使用#define EX_USAGE 64 /* command line usage error */ Most tools like ls also return 2 on invalid arguments. ls这样的大多数工具也会在无效参数上返回2 I also used to return 2 in my scripts but lately I no longer really cared, and simply used 1 in all errors. 我也习惯在我的脚本中返回2 ,但最近我不再真正关心,只是在所有错误中使用1 But let's just place 2 here since it's most common and probably not OS-specific. 但是,让我们在这里放置2 ,因为它是最常见的,可能不是特定于操作系统的。

if [[ $# -ne 1 ]]; then
    echo "Illegal number of parameters"
    exit 2
fi

References 参考


#3楼

It might be a good idea to use arithmetic expressions if you're dealing with numbers. 如果你正在处理数字,那么使用算术表达式可能是个好主意。

if (( $# != 1 )); then
    echo "Illegal number of parameters"
fi

#4楼

On []: !=, =, == ... are string comparison operators and -eq, -gt ... are arithmetic binary ones. On []:!=,=,== ...是字符串比较运算符,-eq,-gt ...是算术二进制运算符。

I would use: 我会用:

if [ "$#" != "1" ]; then

Or: 要么:

if [ $# -eq 1 ]; then

#5楼

A simple one liner that works can be done using: 可以使用以下方法完成简单的单线工作:

[ "$#" -ne 1 ] && ( usage && exit 1 ) || main

This breaks down to: 这分解为:

  1. test the bash variable for size of parameters $# not equals 1 (our number of sub commands) 测试参数大小的bash变量$#not equals 1(我们的子命令数)
  2. if true then call usage() function and exit with status 1 如果为true,则调用usage()函数并退出状态1
  3. else call main() function 否则调用main()函数

Thinks to note: 想一想:

  • usage() can just be simple echo "$0: params" 用法()可以简单回显“$ 0:params”
  • main can be one long script main可以是一个长脚本

#6楼

If you're only interested in bailing if a particular argument is missing, Parameter Substitution is great: 如果您只对缺少某个特定参数的情况感兴趣, 参数替换很棒:

#!/bin/bash
# usage-message.sh

: ${1?"Usage: $0 ARGUMENT"}
#  Script exits here if command-line parameter absent,
#+ with following error message.
#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值