【问题标题】:How to make a multi-character parameter in UNIX using getopt?如何使用 getopt 在 UNIX 中制作多字符参数?
【发布时间】:2010-10-20 05:26:44
【问题描述】:

我正在尝试创建一个 getopt 命令,这样当我将“-ab”参数传递给脚本时, 该脚本会将 -ab 视为单个参数。

#!/bin/sh
args=`getopt "ab":fc:d $*`
set -- $args
for i in $args
do
case "$i" in
        -ab) shift;echo "You typed ab $1.";shift;;
        -c) shift;echo "You typed a c $1";shift;;
esac
done

但是,这似乎不起作用。任何人都可以提供任何帮助吗?

【问题讨论】:

    标签: unix getopt


    【解决方案1】:

    getopt 不支持您要查找的内容。您可以使用单字母 (-a) 或长选项 (--long)。像-ab 这样的东西与-a b 的处理方式相同:作为带有参数b 的选项a。请注意,长选项以两个破折号为前缀。

    【讨论】:

      【解决方案2】:

      我为此苦苦挣扎了很久 - 然后我开始阅读有关 getopt 和 getopts 的文章

      单字符选项和长选项。

      我有类似的要求,我需要有多个多字符输入参数。

      所以,我想出了这个 - 它适用于我的情况 - 希望这对你有帮助

      function show_help {
          echo "usage:  $BASH_SOURCE --input1 <input1> --input2 <input2> --input3 <input3>"
          echo "                     --input1 - is input 1 ."
          echo "                     --input2 - is input 2 ."
          echo "                     --input3 - is input 3 ."
      }
      
      # Read command line options
      ARGUMENT_LIST=(
          "input1"
          "input2"
          "input3"
      )
      
      
      
      # read arguments
      opts=$(getopt \
          --longoptions "$(printf "%s:," "${ARGUMENT_LIST[@]}")" \
          --name "$(basename "$0")" \
          --options "" \
          -- "$@"
      )
      
      
      echo $opts
      
      eval set --$opts
      
      while true; do
          case "$1" in
          h)
              show_help
              exit 0
              ;;
          --input1)  
              shift
              empId=$1
              ;;
          --input2)  
              shift
              fromDate=$1
              ;;
          --input3)  
              shift
              toDate=$1
              ;;
            --)
              shift
              break
              ;;
          esac
          shift
      done
      

      注意 - 我已根据我的要求添加了帮助功能,如果不需要,您可以将其删除

      【讨论】:

        【解决方案3】:

        这不是 unix 的方式,尽管有些人会这样做,例如java -cp classpath.

        Hack:用-b arg 和一个虚拟选项-a 代替-ab arg

        这样,-ab arg 会做你想做的事。 (-b arg 也会;希望这不是错误,而是快捷方式功能...)。

        唯一的变化是你的行:

        -ab) shift;echo "You typed ab $1.";shift;;
        

        变成

        -b) shift;echo "You typed ab $1.";shift;;
        

        【讨论】:

          【解决方案4】:

          getopt 支持长格式。你可以搜索这样的examples。 参见here,例如

          【讨论】:

          • 你能举个例子说明它是如何使用的吗?
          猜你喜欢
          • 1970-01-01
          • 2012-05-03
          • 2013-07-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多