如何在bash中同时支持短选项和长选项?

29

我想在bash脚本中同时支持短选项和长选项,这样就可以:

$ foo -ax --long-key val -b -y SOME FILE NAMES

这可行吗?


1
请参见BashFAQ/035 - Dennis Williamson
尽管被提名的重复问题特别涉及到 getopts,但有几个答案提出了不同的方法。我同意关闭该问题。 - tripleee
1个回答

39

getopt 支持长选项。

http://man7.org/linux/man-pages/man1/getopt.1.html

这里是使用你的参数的示例:

#!/bin/bash

OPTS=`getopt -o axby -l long-key: -- "$@"`
if [ $? != 0 ]
then
    exit 1
fi

eval set -- "$OPTS"

while true ; do
    case "$1" in
        -a) echo "Got a"; shift;;
        -b) echo "Got b"; shift;;
        -x) echo "Got x"; shift;;
        -y) echo "Got y"; shift;;
        --long-key) echo "Got long-key, arg: $2"; shift 2;;
        --) shift; break;;
    esac
done
echo "Args:"
for arg
do
    echo $arg
done

$ foo -ax --long-key val -b -y SOME FILE NAMES的输出结果为:

Got a
Got x
Got long-key, arg: val
Got b
Got y
Args:
SOME
FILE
NAMES

9
某些版本的 getopt 存在参数中某些字符和非选项参数的问题。如果 getopt --test; echo $? 输出 "4",则说明没有问题。如果输出 "0",则说明该版本存在此问题。有关更多信息,请参见 man getopt - Dennis Williamson
同时,POSIXLY_CORRECT环境也是很有用的。 - Lenik
谢吉雷:为什么?你是如何设置的? - Christoph
1
顺便说一下,该链接已经失效了。这里有一个在Archive.Org上的替代链接https://web.archive.org/web/20090130140546/http://linux.about.com/library/cmd/blcmdl1_getopt.htm。 - Adrian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接