-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmd_getopt.sh
executable file
·66 lines (54 loc) · 1.82 KB
/
cmd_getopt.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/bin/bash
# 使用示例:
# ./cmd_getopt.sh -b 123 -a -c456 file file2
# ./cmd_getopt.sh -blong 123 -a --clong=456 file file2
#echo $@
# -o或--options选项后面接可接受的短选项,如ab:c::,表示可接受的短选项为-a -b -c,
# 其中-a选项不接参数,-b选项后必须接参数,-c选项的参数为可选的
# -l或--long选项后面接可接受的长选项,用逗号分开,冒号的意义同短选项
# -n选项后接选项解析错误时提示的脚本名字
ARGS=`getopt -o ab:c:: --long along,blong:,clong:: 'example.sh' -- "$@"`
if [ $? != 0 ]; then
echo "Terminating..."
exit 1
fi
#echo $ARGS
# 将规范化后的命令行参数分配至位置参数($1,$2,...)
eval set -- "${ARGS}"
while true
do
case "$1" in
-a|--along)
echo "Option a"
shift
;;
-b|--blong)
echo "Option b, argument $2"
shift 2
;;
-c|--clong)
case "$2" in
"")
echo "Option c, no argument"
shift 2
;;
*)
echo "Option c, argument $2"
shift 2
;;
esac;;
--)
shift
break
;;
*)
echo "Internal error"
exit 1
;;
esac
done
# 处理剩余的参数
for arg in $@
do
echo "Processing $arg"
done