首页 > 解决方案 > 使用循环解析 ksh 中的长参数和短参数

问题描述

我正在尝试解析 ksh 中的参数。不能像在短选项中那样做getopt我有两个/三个字符。目前我正在使用for循环。它很愚蠢,但我找不到更好的东西。

问题:如何将 option+value 设置为一个单位以便解析?此外,如果eval set -- $option会帮助我,那么我该如何使用它?echo on选项最后没有显示预期的“--”。我假设有什么问题吗?

我正在考虑使用变量来跟踪何时找到选项,但这种方法似乎太混乱且没有必要。

感谢您的时间和帮助。

更新 1:如所指出的那样添加代码。感谢 markp、Andre Gelinas 和 random down-voter 让这个问题变得更好。尝试执行代码第 2 行和第 3 行中给出的脚本 - 或一起传递的短选项和长选项的任何其他组合。

#!/bin/ksh
# bash script1.sh --one 123 --two 234 --three "some string"
# bash script1.sh -o 123 -t 234 -th "some string"

# the following creates problems for short options. 
#options=$(getopt -o o:t:th: -l one:two:three: "--" "$@")

#Since the below `eval set -- "$options"` did not append "--" at the end
#eval set -- "$options"

for i in $@; do
    options="$options $i"
done
options="$options --"

# TODO capture args into variables

到现在为止在 TODO 下面尝试的代码:

for i in $options; do
    echo $i
done

将使用以下方法捕获参数:

while true; do
    case $1 in
        --one|-o) shift; ONE=$1
        ;;
        --two|-t) shift; TWO=$1
        ;;
        --three|-th) shift; THREE=$1
        ;;
        --) shift; break
        ;;
    esac
done

标签: linuxkshstring-parsinggetopt

解决方案


尝试这样的事情:

#!/bin/ksh

#Default value
ONE=123
TWO=456


# getopts configuration
USAGE="[-author?Andre Gelinas <andre.gelinas@foo.bar>]"
USAGE+="[-copyright?2018]"
USAGE+="[+NAME?TestGetOpts.sh]"
USAGE+="[+DESCRIPTION?Try out for GetOps]"
USAGE+="[o:one]#[one:=$ONE?First.]"
USAGE+="[s:second]#[second:=$TWO?Second.]"
USAGE+="[t:three]:[three?Third.]"
USAGE+=$'[+SEE ALSO?\aman\a(1), \aGetOpts\a(1)]'

while getopts "$USAGE" optchar ; do
    case $optchar in
                o)  ONE=$OPTARG ;;
                s)  TWO=$OPTARG ;;
                t)  THREE=$OPTARG ;;
    esac
done

print "ONE = "$ONE
print "TWO = "$TWO
print "THREE = "$THREE

您可以使用--one 或-o。使用 --man 或 --help 也可以。-o 和 -s 也只是数字,但 -t 可以取任何值。希望这有帮助。


推荐阅读