如何使用带有内置猛砸getopts的长选项? [英] How can I use long options with the Bash getopts builtin?

查看:461
本文介绍了如何使用带有内置猛砸getopts的长选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解析使用bash getopts的一个 -temp 选项。我打电话给我的剧本是这样的:

  ./的MyScript -temp /富/酒吧/ someFile

下面是code我使用解析选项。

 而getopts的温度:截图:○:选项;做
    万一$选项
        临时)TMPDIR =$ OPTARG;;
        张)NUMSHOTS =$ OPTARG;;
        O)OUTFILE =$ OPTARG;;
        *)使用;;
    ESAC
DONE
移$(($ OPTIND - 1))[$#-lt 1]安培;&安培;用法


解决方案

如前所述, getopts的只能解析短选项。大多数系统也有一个外部 getopt的命令,但getopt的不规范,一般设计打破,因为它不能处理所有安全参数(与空白和空参数的参数),只有GNU的getopt可以安全地处理它们,但只有当你在GNU特定的方式使用它。

较容易的选择是使用两者都不是,只是想迭代脚本的参数与while循环,做解析自己。请参见 http://mywiki.wooledge.org/BashFAQ/035 一个例子。

I am trying to parse a -temp option with Bash getopts. I'm calling my script like this:

./myscript -temp /foo/bar/someFile

Here is the code I'm using to parse the options.

while getopts "temp:shots:o:" option; do
    case $option in
        temp) TMPDIR="$OPTARG" ;;
        shots) NUMSHOTS="$OPTARG" ;;
        o) OUTFILE="$OPTARG" ;;
        *) usage ;;
    esac
done
shift $(($OPTIND - 1))

[ $# -lt 1 ] && usage

解决方案

As already mentioned, getopts can only parse short options. Most systems also have an external getopt command, but getopt is not standard, and is generally broken by design as it can't handle all arguments safely (arguments with whitespace and empty arguments), only GNU getopt can handle them safely, but only if you use it in a GNU-specific way.

The easier choice is to use neither, just iterate the script's arguments with a while-loop and do the parsing yourself. See http://mywiki.wooledge.org/BashFAQ/035 for an example.

这篇关于如何使用带有内置猛砸getopts的长选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆