【问题标题】:how to use getopt(s) as technique for passing in argument in bash如何使用 getopt(s) 作为在 bash 中传递参数的技术
【发布时间】:2011-07-26 18:26:30
【问题描述】:

有人可以向我展示如何正确使用 getopts 或任何其他我可以在参数中传递的技术的示例吗?我正在尝试在 unix shell/bash 中编写它。我看到有 getopt 和 getopts 并且不确定哪个更好用。最终,我将构建它以添加更多选项。

在这种情况下,我想将文件路径作为输入传递给 shell 脚本,并在输入不正确的情况下放置描述。

export TARGET_DIR="$filepath"

例如:(命令行调用)

./mytest.sh -d /home/dev/inputfiles

如果以这种方式运行,则会出现错误消息或提示正确使用:

./mytest.sh -d /home/dev/inputfiles/

【问题讨论】:

  • 你可以专门测试一下文件夹是否有斜杠,是否存在,是否完全是文件夹——完全独立于你的参数解析方法

标签: bash unix shell getopt getopts


【解决方案1】:

作为用户,我会对一个程序在提供带有尾部斜杠的目录名称时出现错误感到非常恼火。如有必要,您可以将其删除。

一个带有相当完整错误检查的 shell 示例:

#!/bin/sh

usage () {
  echo "usage: $0 -d dir_name"
  echo any other helpful text
}

dirname=""
while getopts ":hd:" option; do
  case "$option" in
    d)  dirname="$OPTARG" ;;
    h)  # it's always useful to provide some help 
        usage
        exit 0 
        ;;
    :)  echo "Error: -$OPTARG requires an argument" 
        usage
        exit 1
        ;;
    ?)  echo "Error: unknown option -$OPTARG" 
        usage
        exit 1
        ;;
  esac
done    

if [ -z "$dirname" ]; then
  echo "Error: you must specify a directory name using -d"
  usage
  exit 1
fi

if [ ! -d "$dirname" ]; then
  echo "Error: the dir_name argument must be a directory
  exit 1
fi

# strip any trailing slash from the dir_name value
dirname="${dirname%/}"

有关 getopts 文档,请查看 bash manual

【讨论】:

  • 谢谢。起初它没有用,但我的 getopts 逻辑在一个函数中而不是在主体中
【解决方案2】:

更正 ':)' 行:

:)  echo "Error: -$OPTARG requires an argument"

因为如果在标志之后没有提供任何值,则 OPTARG 获取标志的名称并将标志设置为“:”,在上面的示例中打印:

Error: -: requires an argument

这不是有用的信息。

同样适用于:

\?)  echo "Error: unknown option -$OPTARG"

感谢您提供此示例!

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 2018-06-05
    • 2013-07-26
    • 2018-02-15
    • 1970-01-01
    • 2010-11-06
    • 2021-01-20
    • 2011-08-06
    相关资源
    最近更新 更多