【问题标题】:Checking for the correct number of arguments检查正确数量的参数
【发布时间】:2011-05-19 12:05:21
【问题描述】:

我如何检查正确数量的参数(一个参数)。如果有人试图在没有传入正确数量的参数的情况下调用脚本,并检查以确保命令行参数确实存在并且是一个目录。

【问题讨论】:

  • @Daniel shell 表示/bin/sh

标签: shell scripting


【解决方案1】:
#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

翻译:如果参数的数量不(数值上)等于 1 或第一个参数不是目录,则将使用情况输出到 stderr 并以失败状态代码退出。

更友好的错误报告:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

【讨论】:

  • @Andrew K:它在哪一行报告这个?如果是“if”行,请尝试删除两个子句之一,使其成为if [ "$#" -ne 1 ] ; thenif ! [ -d "$1" ]; then,看看哪个子句导致了问题。
  • 我明白了,谢谢。文件名不存在怎么办?
  • 不存在 == 就-d 而言,它不是董事。如果您想添加单独的检查,可以使用-e 来检查是否存在。
  • if [ -e "$1" ] then echo "$1 : No such directory" exit 1 fi
  • @Andrew K:您想反转支票。 -e 如果文件存在则返回 true。我在答案中添加了更友好的错误报告。
【解决方案2】:

猫脚本.sh

    var1=$1
    var2=$2
    if [ "$#" -eq 2 ]
    then
            if [ -d $var1 ]
            then
            echo directory ${var1} exist
            else
            echo Directory ${var1} Does not exists
            fi
            if [ -d $var2 ]
            then
            echo directory ${var2} exist
            else
            echo Directory ${var2} Does not exists
            fi
    else
    echo "Arguments are not equals to 2"
    exit 1
    fi

如下执行 -

./script.sh directory1 directory2

输出会像 -

directory1 exit
directory2 Does not exists

【讨论】:

    【解决方案3】:

    您可以使用 "$#" 检查命令行中传递的参数总数 例如,我的 shell 脚本名称是 hello.sh

    sh hello.sh hello-world
    # I am passing hello-world as argument in command line which will b considered as 1 argument 
    if [ $# -eq 1 ] 
    then
        echo $1
    else
        echo "invalid argument please pass only one argument "
    fi
    

    输出将是hello-world

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      相关资源
      最近更新 更多