如何在bash中同时支持短期和长期期权?

时间:2010-11-15 02:02:24

标签: bash getopt getopt-long

我想支持bash脚本中的短期和长期选项,因此可以:

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

有可能吗?

1 个答案:

答案 0 :(得分:37)

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