如何在UNIX中使用getopt生成多字符参数?
我试图生成一个getopt命令,这样当我将“-ab”参数传递给脚本时, 该脚本将把-ab视为单个参数如何在UNIX中使用getopt生成多字符参数?,unix,getopt,Unix,Getopt,我试图生成一个getopt命令,这样当我将“-ab”参数传递给脚本时, 该脚本将把-ab视为单个参数 #!/bin/sh args=`getopt "ab":fc:d $*` set -- $args for i in $args do case "$i" in -ab) shift;echo "You typed ab $1.";shift;; -c) shift;echo "You typed a c $1";shift;; esac done 然而,这似乎
#!/bin/sh
args=`getopt "ab":fc:d $*`
set -- $args
for i in $args
do
case "$i" in
-ab) shift;echo "You typed ab $1.";shift;;
-c) shift;echo "You typed a c $1";shift;;
esac
done
然而,这似乎不起作用。有人能提供帮助吗?getopt支持长格式。你可以这样搜索。
例如,请参见getopt不支持您正在查找的内容。您可以使用单个字母(
-a
)或长选项(--long
)。类似于-ab
的内容与-ab
的处理方式相同:作为带有参数b
的选项a
。请注意,长选项的前缀是两个破折号。我一直在努力解决这个问题,然后我开始阅读关于getopt和getopts的文章
单字符选项和长字符选项
我有类似的要求,需要有多个multichar输入参数
所以,我想出了这个-它在我的情况下起作用-希望这对你有帮助
function show_help {
echo "usage: $BASH_SOURCE --input1 <input1> --input2 <input2> --input3 <input3>"
echo " --input1 - is input 1 ."
echo " --input2 - is input 2 ."
echo " --input3 - is input 3 ."
}
# 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
h)
show_help
exit 0
;;
--input1)
shift
empId=$1
;;
--input2)
shift
fromDate=$1
;;
--input3)
shift
toDate=$1
;;
--)
shift
break
;;
esac
shift
done
函数显示\u帮助{
echo“用法:$BASH\u源--input1--input2--input3”
echo“-input1”是输入1
echo“-input2”是输入2
echo“-input3”是输入3
}
#读取命令行选项
参数列表=(
“输入1”
“输入2”
“输入3”
)
#读参数
opts=$(getopt)\
--longoptions“$(printf”%s:,“${ARGUMENT_LIST[@]}”)\
--名称“$(基本名称“$0”)”\
--选项“”\
-- "$@"
)
echo$opts
评估集--$opts
虽然真实;做
案件“$1”
h)
伸出援手
出口0
;;
--输入1)
转移
empId=$1
;;
--输入2)
转移
fromDate=$1
;;
--输入3)
转移
toDate=1美元
;;
--)
转移
打破
;;
以撒
转移
完成
注意-我已经根据我的要求添加了帮助功能,如果不需要,您可以删除它这不是unix的方式,尽管有一些这样做,例如
java-cp classpath
Hack:代替-ab arg
,使用-b arg
和一个虚拟选项-a
这样,-ab arg
就能满足您的需求。(-b arg
也会;希望这不是一个bug,而是一个快捷功能…)
唯一的变化是您的线路:
-ab) shift;echo "You typed ab $1.";shift;;
变成
-b) shift;echo "You typed ab $1.";shift;;
你能举个例子说明这是如何使用的吗?