Bash getopts 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9880261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:51:50  来源:igfitidea点击:

Bash getopts command

bashgetopts

提问by spatara

I am following IBM's example from their website:

我正在关注他们网站上的 IBM 示例:

(listing #5) http://www.ibm.com/developerworks/library/l-bash-parameters/index.html

(清单 5)http://www.ibm.com/developerworks/library/l-bash-parameters/index.html

#!/bin/bash
echo "OPTIND starts at $OPTIND"
while getopts ":pq:" optname
  do
    case "$optname" in
      "p")
        echo "Option $optname is specified"
        ;;
      "q")
        echo "Option $optname has value $OPTARG"
        ;;
      "?")
        echo "Unknown option $OPTARG"
        ;;
      ":")
        echo "No argument value for option $OPTARG"
        ;;
      *)
      # Should not occur
        echo "Unknown error while processing options"
        ;;
    esac
    echo "OPTIND is now $OPTIND"
  done

All I want to to is have an option whose name is more than 1 letter. ie -pppp and -qqqq instead of -p and -q.

我想要的只是一个名称超过 1 个字母的选项。即 -pppp 和 -qqqq 而不是 -p 和 -q。

I have written my program and implementing -help is giving me a problem...

我已经编写了我的程序并且实施 -help 给了我一个问题......

回答by je4d

For conventional shell commands, -helpis equivalent to -h -e -l -p, so if you parse "-help" with getoptsit will treat it as four separate arguments. Because of this you can't have multi-letter arguments prefixed with only a single hyphen unless you want to do all the parsing yourself. By convention, options that aren't just single characters (aka "long options") are preceded by two dashes instead to make things unambiguous.

对于传统的 shell 命令,-help相当于-h -e -l -p,所以如果你用getopts它解析“-help”,它将把它当作四个单独的参数。因此,除非您想自己进行所有解析,否则您不能只使用一个连字符作为前缀的多字母参数。按照惯例,不只是单个字符的选项(又名“长选项”)前面有两个破折号,而不是使事情明确。

The convention for help text is to support both -hand --help.

帮助文本的约定是同时支持-h--help

Unfortunately bash's getoptsbuiltin doesn't support long options, but on all common Linux distributions there's a separate getoptutility that can be used instead that does support long options.

不幸的是,bash 的getopts内置不支持长选项,但在所有常见的 Linux 发行版上,都有一个单独的getopt实用程序可以代替它来支持长选项。

There's more discussion of the topic in this answer

这个答案中有更多关于该主题的讨论

回答by Umae

Upfloor's are right. the getopt utility support long options while you can use --option. Maybe you can try this.

楼上说的对 getopt 实用程序支持长选项,而您可以使用 --option。也许你可以试试这个。

#!/bin/bash
args=`getopt -l help :pq: $*`
for i in $args; do
    case $i in
    -p) echo "-p"
        ;;
    -q) shift;
        optarg=;
        echo "-q $optarg"
        ;;
    --help)
        echo "--help"
        ;;
    esac
done