3

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

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

export TARGET_DIR="$filepath"

例如:(在命令行调用)

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

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

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

2 回答 2

6

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

一个非常完整的错误检查的 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 手册

于 2011-07-26T19:25:33.390 回答
0

更正 ':)' 行:

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

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

Error: -: requires an argument

这不是有用的信息。

同样适用于:

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

感谢您提供此示例!

于 2013-07-11T16:20:52.217 回答