本文翻译自: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 ]; thenecho "Illegal number of parameters"
fi

Or 要么

if test "$#" -ne 1; thenecho "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 ]]; thenecho "Illegal number of parameters"exit 2
fi

References 参考

  • Bash Conditional Expressions Bash条件表达式
  • Conditional Constructs 条件构造
  • Pattern Matching 模式匹配
  • Word Splitting 单词分裂
  • Filename Expansion (prev. Pathname Expansion) 文件名扩展(prev。路径名扩展)
  • Simple Commands 简单的命令

#3楼

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

if (( $# != 1 )); thenecho "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

检查传递给Bash脚本的参数数量相关推荐

  1. java嵌入groovy脚本,java-如何捕获传递给Groovy脚本的参数?

    它与Java非常相似,您可以使用相同的Java语法. 例如. class TestExecutor { public static void main(def args) { println(&quo ...

  2. 将参数传递给Bash函数

    我试图搜索如何在Bash函数中传递参数,但是出现的是如何从命令行传递参数. 我想在我的脚本中传递参数. 我试过了: myBackupFunction("..", "... ...

  3. Linux下杂乱无章的Bash脚本传入参数--如何解析?

    无论是外置的getopt命令,亦或是bash内置的getopts函数,都对bash脚本的传入参数做了一些规定,比如强制规定了短参数"-t 1",长参数"--test 1& ...

  4. python cmd命令 循环传参数_将参数从cmd传递给python脚本

    我在 python中编写脚本并通过输入以下命令运行cmd: C:\> python script.py 我的一些脚本包含基于标志调用的单独算法和方法. 现在我想通过cmd直接传递标志,而不是必须 ...

  5. nginx变量传递给php,php-从nginx将参数传递给auth_request模块

    我想转播一个实时HLS流.我想使用auth_request模块.我想通过传递密钥来检查请求是否有效.所以像:http://domain.com/hls/stream.m3u8?key=xxxxxxx ...

  6. 处理除第一个之外的所有参数(在bash脚本中)

    本文翻译自:Process all arguments except the first one (in a bash script) I have a simple script where the ...

  7. 如何在CLI命令行下运行PHP脚本,同时向PHP脚本传递参数?

    如何在命令行下运行PHP脚本[带参数] 创建一个简单的文本文件,其中包含有以下PHP代码,并把它保存为hello.php: <?php echo "Hello from the CLI ...

  8. bash脚本编程入门_Bash编程入门

    bash脚本编程入门 对Unix的最初希望之一是,它将使日常的计算机用户能够微调其计算机以适应其独特的工作风格. 在过去的几十年中,对计算机定制的期望已经降低,许多用户将他们收集的应用程序和网站视为他 ...

  9. Linux脚本:Bash脚本看这一篇就够了

    前言 Linux脚本有很多解析器(Shell),不同解析器要求的脚本语法是不一样的.系统在解析脚本时,如果没有在脚本声明指定解析器,则会采用系统默认解析器来对脚本进行解析.sh是非常重要解析器,历史很 ...

最新文章

  1. 优秀好文收录(持续更新...)
  2. freemark静态页面中文乱码
  3. USB转串口 FT232/PL2303/CH340 驱动以及使用体会
  4. codeforces 41A-C语言解题报告
  5. python123测验9程序题答案_Django ORM 练习题及答案_python_脚本之家
  6. 包管理器_包管理器的演变
  7. C++ STL之vector详解
  8. numpy线性代数基础 - Python和MATLAB矩阵处理的不同
  9. 海康、大华、科达、华为摄像机的二次开发Demo、SDK
  10. python自主学习——Unicode
  11. 2017中国云计算技术大会将于5月18-19日在京召开
  12. ai的智能发展不会超越人类_人工智能:超越炒作
  13. 网络流量分析详解(包含OSI七层模型、TCP协议及Wireshark工具用法)
  14. Java 多线程线程安全(面试概念解答二)
  15. 教你如何在腾讯云阿里云薅羊毛
  16. No unique bean of type..... Unsatisfied dependency of type
  17. 关于在mathtype中输入微分符号点
  18. 词云库学习--python习题
  19. MBA联考-20101227
  20. 接受电话面试时有哪些要注意的

热门文章

  1. Android自定义组件之简单组合
  2. 【Linux】【C/C++】十叉非完全树的构造和重构
  3. Android动态修改选中和不选中的Button图片颜色
  4. android中button点击频率控制
  5. php json设置编码,php实现json编码的方法,phpjson编码
  6. python编程基础知识点上的问题_python编程入门之二:必备基础知识
  7. (006) java后台开发之基本数据类型
  8. obj + mtl 格式说明
  9. bash之预定义变量
  10. (笔记)电路设计(十四)之放大器的应用