【发布时间】:2018-07-22 15:47:10
【问题描述】:
我正在尝试解析 ksh 中的参数。 getopt 不能与短选项中的相同,我有两个/三个字符。目前我正在使用 for 循环。它很愚蠢,但我找不到更好的东西。
问题:如何将option+value设置为一个单元进行解析? 另外,如果 eval set -- $option 对我有帮助,那么我该如何使用它呢? option 上的 echo 未在末尾显示预期的“--”。我假设有什么问题吗?
我正在考虑使用变量来跟踪何时找到选项,但这种方法似乎太混乱且没有必要。
感谢您的时间和帮助。
更新 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
【问题讨论】:
-
嗨,如果有人觉得这个问题没有帮助,我很抱歉。有没有办法改进这个问题?
-
我猜有人投了反对票,因为......你没有提供你试图解析的例子,也没有你尝试过的任何代码 sn-ps......或者可能是因为快速搜索将显示涵盖同一主题的多个问答(例如,此bash/getops post)
-
您能否发布您尝试过的内容,并附上工作示例。
标签: linux ksh string-parsing getopt