如何在Bash的getopts内置命令中使用长选项?

61

我正在尝试使用Bash的getopts解析-temp选项。我这样调用我的脚本:

./myscript -temp /foo/bar/someFile

这是我用来解析选项的代码。

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

可能是如何在Bash中解析命令行参数?的重复问题。 - rds
6
我不同意它是重复的。那个问题更加通用,是关于如何解析,而这个问题则更具体,是关于如何解析长选项的。 - brat
9个回答

111

正如其他人所解释的那样,getopts不能解析长选项。你可以使用getopt,但它不可移植(而且在某些平台上出现问题...)

作为一种解决方法,您可以实现一个shell循环。这里是一个示例,在使用标准getopts命令之前将长选项转换为短选项(在我看来更简单):

# Transform long options to short ones
for arg in "$@"; do
  shift
  case "$arg" in
    '--help')   set -- "$@" '-h'   ;;
    '--number') set -- "$@" '-n'   ;;
    '--rest')   set -- "$@" '-r'   ;;
    '--ws')     set -- "$@" '-w'   ;;
    *)          set -- "$@" "$arg" ;;
  esac
done

# Default behavior
number=0; rest=false; ws=false

# Parse short options
OPTIND=1
while getopts "hn:rw" opt
do
  case "$opt" in
    'h') print_usage; exit 0 ;;
    'n') number=$OPTARG ;;
    'r') rest=true ;;
    'w') ws=true ;;
    '?') print_usage >&2; exit 1 ;;
  esac
done
shift $(expr $OPTIND - 1) # remove options from positional parameters

14
除了指出“非法选项——-”之外,这真是太好了。如果传递无效的参数,它没有适当地通知用户。我在我的脚本中添加了以下内容以帮助解决此问题: "--"*) usage ${arg}; exit 2;; - bshacklett
这可能是一个好主意。我的例子可以通过相同的方式进行改进,以允许像“--separator=STRING”这样的语法。我选择实现一个简单的循环,并不允许所有可能的语法。它可以被改进。 - mcoolive
1
运行得很好。感谢您分享您的解决方案。 - Meow Kim
1
请添加一个需要参数的长选项。 - chrisinmtown
1
当您的命令在位置参数之后还有其他参数时,通常是在命令行上的 -- 之后,@dotnetCarpenter shift $(expr $OPTIND - 1) 是非常有用的。 - mcoolive
显示剩余10条评论

55

getopts只能解析短选项。

大多数系统也有一个外部的getopt命令,但是getopt不是标准的,并且通常由于其设计缺陷而不能安全地处理所有参数(包括带空格和空参数的参数),只有GNU getopt可以安全地处理它们,但前提是您必须以GNU特定的方式使用它。

更简单的方法是不使用任何工具,而是使用while循环迭代脚本的参数并自行进行解析。

请参见http://mywiki.wooledge.org/BashFAQ/035中的示例。


4
没必要重新发明轮子,在这里只需使用getopts并查找其他解析长参数的方式,或者像@mcoolive在这里展示的那样进行技巧处理。 - ndoc

3
最简单的方法是利用 getopt--longoptions,尝试一下,希望有用。
# 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
    --input1)  
        shift
        empId=$1
        ;;
    --input2)  
        shift
        fromDate=$1
        ;;
    --input3)  
        shift
        toDate=$1
        ;;
      --)
        shift
        break
        ;;
    esac
    shift
done

而这就是如何调用 shell 脚本

myscript.sh --input1 "ABC" --input2 "PQR" --input2 "XYZ"

3

getopts被shell程序用于解析仅限1个字符的位置参数(不包括GNU风格的长选项(--myoption)或XF86风格的长选项(-myoption))。


1

确实,bash内置的getopts只能解析短选项, 但您仍然可以添加几行脚本来使getopts处理长选项。

这是在http://www.uxora.com/unix/shell-script/22-handle-long-options-with-getopts中找到的代码的一部分。

  #== set options ==#
SCRIPT_OPTS=':fbF:B:-:h'
typeset -A ARRAY_OPTS
ARRAY_OPTS=(
    [foo]=f
    [bar]=b
    [foobar]=F
    [barfoo]=B
    [help]=h
    [man]=h
)

  #== parse options ==#
while getopts ${SCRIPT_OPTS} OPTION ; do
    #== translate long options to short ==#
    if [[ "x$OPTION" == "x-" ]]; then
        LONG_OPTION=$OPTARG
        LONG_OPTARG=$(echo $LONG_OPTION | grep "=" | cut -d'=' -f2)
        LONG_OPTIND=-1
        [[ "x$LONG_OPTARG" = "x" ]] && LONG_OPTIND=$OPTIND || LONG_OPTION=$(echo $OPTARG | cut -d'=' -f1)
        [[ $LONG_OPTIND -ne -1 ]] && eval LONG_OPTARG="\$$LONG_OPTIND"
        OPTION=${ARRAY_OPTS[$LONG_OPTION]}
        [[ "x$OPTION" = "x" ]] &&  OPTION="?" OPTARG="-$LONG_OPTION"

        if [[ $( echo "${SCRIPT_OPTS}" | grep -c "${OPTION}:" ) -eq 1 ]]; then
            if [[ "x${LONG_OPTARG}" = "x" ]] || [[ "${LONG_OPTARG}" = -* ]]; then 
                OPTION=":" OPTARG="-$LONG_OPTION"
            else
                OPTARG="$LONG_OPTARG";
                if [[ $LONG_OPTIND -ne -1 ]]; then
                    [[ $OPTIND -le $Optnum ]] && OPTIND=$(( $OPTIND+1 ))
                    shift $OPTIND
                    OPTIND=1
                fi
            fi
        fi
    fi

    #== options follow by another option instead of argument ==#
    if [[ "x${OPTION}" != "x:" ]] && [[ "x${OPTION}" != "x?" ]] && [[ "${OPTARG}" = -* ]]; then 
        OPTARG="$OPTION" OPTION=":"
    fi

    #== manage options ==#
    case "$OPTION" in
        f  ) foo=1 bar=0                    ;;
        b  ) foo=0 bar=1                    ;;
        B  ) barfoo=${OPTARG}               ;;
        F  ) foobar=1 && foobar_name=${OPTARG} ;;
        h ) usagefull && exit 0 ;;
        : ) echo "${SCRIPT_NAME}: -$OPTARG: option requires an argument" >&2 && usage >&2 && exit 99 ;;
        ? ) echo "${SCRIPT_NAME}: -$OPTARG: unknown option" >&2 && usage >&2 && exit 99 ;;
    esac
done
shift $((${OPTIND} - 1))

Here is a test:

# Short options test
$ ./foobar_any_getopts.sh -bF "Hello world" -B 6 file1 file2
foo=0 bar=1
barfoo=6
foobar=1 foobar_name=Hello world
files=file1 file2

# Long and short options test
$ ./foobar_any_getopts.sh --bar -F Hello --barfoo 6 file1 file2
foo=0 bar=1
barfoo=6
foobar=1 foobar_name=Hello
files=file1 file2

否则在最近的Korn Shell ksh93中,getopts可以自然地解析长选项并且甚至显示类似于man page的页面。(见http://www.uxora.com/unix/shell-script/20-getopts-with-man-page-and-long-options)
Michel VONGVILAY。

不错,谢谢。不幸的是,如果参数包含“=”或参数为空字符串,则会出现错误。我应该建议一个支持“=”和空字符串作为参数的版本吗? - Beef Eater

1
尽管这个问题是在2年前发布的,但我发现自己也需要支持XFree86风格的长选项;而且我还想从getopts中获取所需内容。考虑GCC开关-rdynamic。我将r标记为标志字母,并期望$OPTARG中包含dynamic...但是,我想拒绝-r dynamic,同时接受其他跟随r的选项。
下面的想法建立在这样一个观察基础上:$OPTIND如果后面跟着空格(间隙),它将比其他情况多1。因此,我定义了一个bash变量来保存$OPTIND的先前值,称为$PREVOPTIND,并在while循环结束时更新它。如果$OPTIND$PREVOPTIND大1,则表示没有间隙(例如-rdynamic);此时$GAP设置为false。相反,如果$OPTIND$PREVOPTIND大2,则表示有间隙(例如-r dynamic);此时$GAP设置为true
usage() { echo usage: error from $1; exit -1; }

OPTIND=1
PREVOPTIND=$OPTIND
while getopts "t:s:o:" option; do
  GAP=$((OPTIND-(PREVOPTIND+1)))
  case $option in
    t) case "${OPTARG}" in
         emp)                  # i.e. -temp
           ((GAP)) && usage "-${option} and ${OPTARG}"
           TMPDIR="$OPTARG"
           ;;
         *)
           true
           ;;
       esac
       ;;
    s) case "${OPTARG}" in
         hots)                 # i.e. -shots
           ((GAP)) && usage
           NUMSHOTS="$OPTARG"
           ;;
         *) usage "-${option} and ${OPTARG}" ;;
       esac
       ;;
    o) OUTFILE="$OPTARG" ;;
    *) usage "-${option} and ${OPTARG}" ;;
  esac
  PREVOPTIND=$OPTIND
done
shift $(($OPTIND - 1))

0
感谢 @mcoolive。
我能够使用你的 $@ 想法将整个单词和长选项转换为单字母选项。想要提醒任何使用这个想法的人,我还必须在通过 getopts 循环运行参数之前包括 shift $(expr $OPTIND - 1)
完全不同的目的,但这很有效。
# convert long word options to short word for ease of use and portability

for argu in "$@"; do
  shift
  #echo "curr arg = $1"
  case "$argu" in
"-start"|"--start")
                   # param=param because no arg is required
                   set -- "$@" "-s"
                   ;;
"-pb"|"--pb"|"-personalbrokers"|"--personalbrokers")
                   # pb +arg required
                   set -- "$@" "-p $1"; #echo "arg=$argu"
                   ;;
"-stop"|"--stop")
                   # param=param because no arg is required 
                   set -- "$@" "-S" 
                   ;;
                #  the catch all option here removes all - symbols from an
                #  argument. if an option is attempted to be passed that is
                #  invalid, getopts knows what to do...
               *)  [[ $(echo $argu | grep -E "^-") ]] && set -- "$@" "${argu//-/}" || echo "no - symbol. not touching $argu" &>/dev/null
                   ;;
esac
done

#echo -e "\n final option conversions = $@\n"
# remove options from positional parameters for getopts parsing
shift $(expr $OPTIND - 1)

declare -i runscript=0
# only p requires an argument hence the p:
 while getopts "sSp:" param; do
[[ "$param" == "p" ]] && [[ $(echo $OPTARG | grep -E "^-") ]] && funcUsage "order" 
#echo $param
#echo "OPTIND=$OPTIND"
case $param in
s)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       arg0=start
       ;;
 p)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       [[ "$OPTARG" == "all" ]] && echo -e "argument \"$OPTARG\" accepted. continuing." && (( runscript += 1 )) || usage="open"
       [[ $( echo $pbString | grep -w "$OPTARG" ) ]] && echo -e "pb $OPTARG was validated. continuing.\n" && (( runscript += 1 )) || usage="personal"
       [[ "$runscript" -lt "1" ]] && funcUsage "$usage" "$OPTARG"
       arg0=start
       ;;
S)
       OPTARG=${OPTARG/ /}
       getoptsRan=1
       echo "$param was passed and this is it's arg $OPTARG"
       arg0=stop
       ;;
*)
       getoptsRan=1
       funcUsage
       echo -e "Invalid argument\n"
       ;;
esac
done
funcBuildExcludes "$@"
shift $((OPTIND-1))

0

你不能使用getopts Bash内置命令处理长选项,除非你自己构建解析函数。相反,你应该查看/usr/bin/getopt二进制文件(在我的系统上由util-linux包提供;你的情况可能有所不同)。

请参阅getopt(1)以获取特定的调用选项。


我认为 /usr/bin/getopt 也不支持长选项。 - Christopher Barber

-1

如果您在使用内置的getopts时遇到问题,可以尝试以下简单的DIY方法:

使用:

$ ./test-args.sh --a1 a1 --a2 "a 2" --a3 --a4= --a5=a5 --a6="a 6"
a1 = "a1"
a2 = "a 2"
a3 = "TRUE"
a4 = ""
a5 = "a5"
a6 = "a 6"
a7 = ""

脚本:

#!/bin/bash

function main() {
    ARGS=`getArgs "$@"`

    a1=`echo "$ARGS" | getNamedArg a1`
    a2=`echo "$ARGS" | getNamedArg a2`
    a3=`echo "$ARGS" | getNamedArg a3`
    a4=`echo "$ARGS" | getNamedArg a4`
    a5=`echo "$ARGS" | getNamedArg a5`
    a6=`echo "$ARGS" | getNamedArg a6`
    a7=`echo "$ARGS" | getNamedArg a7`

    echo "a1 = \"$a1\""
    echo "a2 = \"$a2\""
    echo "a3 = \"$a3\""
    echo "a4 = \"$a4\""
    echo "a5 = \"$a5\""
    echo "a6 = \"$a6\""
    echo "a7 = \"$a7\""

    exit 0
}


function getArgs() {
    for arg in "$@"; do
        echo "$arg"
    done
}


function getNamedArg() {
    ARG_NAME=$1

    sed --regexp-extended --quiet --expression="
        s/^--$ARG_NAME=(.*)\$/\1/p  # Get arguments in format '--arg=value': [s]ubstitute '--arg=value' by 'value', and [p]rint
        /^--$ARG_NAME\$/ {          # Get arguments in format '--arg value' ou '--arg'
            n                       # - [n]ext, because in this format, if value exists, it will be the next argument
            /^--/! p                # - If next doesn't starts with '--', it is the value of the actual argument
            /^--/ {                 # - If next do starts with '--', it is the next argument and the actual argument is a boolean one
                # Then just repla[c]ed by TRUE
                c TRUE
            }
        }
    "
}


main "$@"

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