提问人:Waffles 提问时间:10/20/2010 更新时间:4/19/2022 访问量:41846
如何使用 getopt 在 UNIX 中制作多字符参数?
How to make a multi-character parameter in UNIX using 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
但是,这似乎行不通。任何人都可以提供任何帮助吗?
答:
-5赞
ghostdog74
10/20/2010
#1
getopt 支持长格式。您可以在 SO 中搜索此类示例。 例如,请参阅此处
评论
5赞
Waffles
10/20/2010
您能举例说明如何使用它吗?
17赞
paprika
10/20/2010
#2
GetOpt 不支持您要查找的内容。您可以使用单字母 () 或长选项 ()。类似的东西的处理方式与 : 作为带参数的选项相同。请注意,长选项以两个破折号为前缀。-a
--long
-ab
-a b
a
b
评论
3赞
Philippe Fanaro
6/1/2023
那么你能告诉我们如何做到这一点吗?--long
2赞
Ashish Shetkar
4/2/2019
#3
我为此苦苦挣扎了很长时间 - 然后我开始阅读有关 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
注意 - 我根据我的要求添加了帮助功能,如果不需要,您可以将其删除
2赞
hyperpallium
7/6/2019
#4
这不是 unix 的方式,尽管有些人这样做,例如.java -cp classpath
Hack:代替 , have 和 a dummy 选项。-ab arg
-b arg
-a
这样,就可以做你想做的事。(也会;希望这不是一个错误,而是一个快捷方式功能......-ab arg
-b arg
唯一的变化是你的行:
-ab) shift;echo "You typed ab $1.";shift;;
成为
-b) shift;echo "You typed ab $1.";shift;;
1赞
Sloth
4/19/2022
#5
GNU getopt 有 --alternative 选项
-a, --alternative
Allow long options to start with a single '-'.
例:
#!/usr/bin/env bash
SOPT='a:b'
LOPT='ab:'
OPTS=$(getopt -q -a \
--options ${SOPT} \
--longoptions ${LOPT} \
--name "$(basename "$0")" \
-- "$@"
)
if [[ $? > 0 ]]; then
exit 2
fi
A=
B=false
AB=
eval set -- $OPTS
while [[ $# > 0 ]]; do
case ${1} in
-a) A=$2 && shift ;;
-b) B=true ;;
--ab) AB=$2 && shift ;;
--) ;;
*) ;;
esac
shift
done
printf "Params:\n A=%s\n B=%s\n AB=%s\n" "${A}" "${B}" "${AB}"
$ ./test.sh -a aaa -b -ab=test
Params:
A=aaa
B=true
AB=test
评论