【问题标题】:How do you use getopts?你如何使用getopts?
【发布时间】:2011-11-30 17:15:24
【问题描述】:

bash 脚本中使用 getopts 的最简单、最直接的方法是什么。

如果我有一个名为:myscript 的脚本,它 CAN 接受参数:-p -r -s -x

if argument x then exit
if argument p then echo "port 10"
if argument s then add 2+2
if argument r then echo env 

这是一个假设的脚本,但我只是想看看如何完成此操作的示例。

【问题讨论】:

标签: bash getopts


【解决方案1】:
usage()
{
    echo "Usage: $0 [-o <offset>] [-h];"
    exit 0;
}

# -o (offset) need a value
# -h prints help
offset=0    # 0 is default offset

while getopts o:s opt
do
    case "$opt" in
    d)  offset="$OPTARG";; # changing offset
    s)  usage              # calls function "usage"
    \?) echo "$OPTARG is an unknown option"
        exit 1;; # all other options
    esac
done

shift $((OPTIND-1))

【讨论】:

  • shift $OPTIND-1 表达式在哪个 shell 中起作用?它通常必须是 $(($OPTIND - 1)) 之类的东西,不是吗?
  • 甚至:$((OPTIND - 1)),这是现在的标准。
【解决方案2】:
while getopts :xpsr opt; do
   case $opt in
     x ) exit                                ;;
     p ) echo port 10                        ;;
     s ) (( 2 + 2 ))                         ;;
     r ) echo env                            ;;
    \? ) echo "${0##*/}" [ -xpsr ]; exit 1   ;;
  esac
done

【讨论】:

  • 甜蜜.. 谢谢 Dimitre。但是这最后一部分是做什么的呢? \? ) echo "${0##*/}" [-xpsr]; 1号出口
  • 打印使用情况,如果通过了无效选项,则存在。
  • 不,我没有(也许我从字面上看问题:))。我也没有展示如何处理选项的参数...
猜你喜欢
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 2012-10-24
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
相关资源
最近更新 更多