检查数量的参数bash脚本的 [英] checking number of arguments bash script

查看:119
本文介绍了检查数量的参数bash脚本的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,如果我的脚本得到太多(或过少)参数打印错误消息。

I'm trying to print an error message if my script gets too many (or too few) arguments.

我尝试以下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? (I'm totally new to bash)

推荐答案

就像任何其他简单的命令, [...] 测试需要它的参数之间的空格。

Just like any other simple command, [ ... ] or test requires spaces between its arguments.

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

或者

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

当猛砸,preFER使用

[[]] ,而不是因为它不会做字的拆分和路径扩展到它的变量引用可能没有必要除非它是一个前pression的一部分。

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.

[[ $# -ne 1 ]]

它也有一些其他的功能,如不带引号的情况分组,模式匹配(扩展模式匹配 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> ]]

对于纯算术EX pressions,使用(())来仍有一些可能会更好,但他们仍然有可能在 [ []] ,其算术运算符如 -eq -ne -lt -le -gt -ge :

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:

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.

  • Bash Conditional Expressions
  • Conditional Constructs
  • Pattern Matching
  • Word Splitting
  • Filename Expansion (prev. Pathname Expansion)

这篇关于检查数量的参数bash脚本的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆