如何在内置Bash getopts的情况下使用长选项?

问题描述 投票:32回答:9

我试图用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 command-line-arguments getopts
9个回答
41
投票

getopts只能解析短期权。

大多数系统也有一个外部getopt命令,但getopt不是标准的,并且通常被设计破坏,因为它不能安全地处理所有参数(带有空格和空参数的参数),只有GNU getopt可以安全地处理它们,但仅限于您以GNU特定的方式使用它。

更简单的选择是不使用,只需用while循环迭代脚本的参数并自己进行解析。

有关示例,请参阅http://mywiki.wooledge.org/BashFAQ/035


48
投票

正如其他人所解释的那样,getopts并没有解析长期选择。你可以使用getopt,但它不是可移植的(它在某些平台上被破坏了......)

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

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

# Default behavior
rest=false; ws=false

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

2
投票

shell程序使用getopts来解析仅1个字符的位置参数(没有GNU样式的长选项( - myoption)或XF86样式的长选项(-myoption))


1
投票

虽然这个问题是在2年前发布的,但我发现自己也需要支持XFree86风格的长选项;我也想从getopts中拿走我能做的。考虑GCC开关-rdynamic。我将r标记为旗帜字母,并期待dynamic内的$OPTARG ...但是,我想拒绝-r dynamic,同时接受r之后的其他选项。

我在下面提出的想法是基于观察到$OPTIND将比其他情况更大,如果空间(间隙)跟随旗帜。因此,我定义一个bash变量来保存$OPTIND的前一个值,称为$PREVOPTIND,并在while循环结束时更新它。如果$OPTIND1大于$PREVOPTIND,我们没有差距(即-rdynamic);和$GAP设置为false。如果相反$OPTIND2大于$PREVOPTIND,我们确实有一个间隙(例如-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))

1
投票

实现这一目标的最简单方法是使用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"

0
投票

你不能使用getopts Bash内置的长选项 - 至少,不必构建自己的解析函数。您应该查看/ usr / bin / getopt二进制文件(由我的系统提供的util-linux包;您的里程可能会有所不同)。

有关特定的调用选项,请参阅getopt(1)。


0
投票

确实,内置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))

这是一个测试:

# 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可以自然地解析长选项,甚至可以显示手册页。 (见http://www.uxora.com/unix/shell-script/20-getopts-with-man-page-and-long-options

Michel VONGVILAY。


0
投票

感谢@mcoolive。

我能够使用你的$ @ idea将整个单词和长选项转换为单个字母选项。想要通知使用这个想法的任何人,我必须在通过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时遇到麻烦,请使用简单的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 "$@"
© www.soinside.com 2019 - 2024. All rights reserved.