介绍
平时使用命令的时候,我们经常会使用–help查看选项列表进行使用,那么在命令内部是怎么获取到我们的选项以及参数使用的呢?
今天就来介绍下这个命令1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
### 用法
首先我们先来看个简单的小例子
```sh
➜ /Users/ramon.zhang/project/shell/test > sh getopts.sh -a hello
getopts test
the -a option is: hello
➜ /Users/ramon.zhang/project/shell/test > cat getopts.sh
#!/bin/bash
echo "getopts test"
while getopts a: option
do
case $option
in
a)
echo "the -a option is: $OPTARG"
;;
\?)
;;
esac
done
从上面我们可以看到,通过使用getopts,我们可以读取到-a以及其参数。一切都很顺利,那么第一个疑问点来了,getopts后面的option_string是1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19```sh
➜ /Users/ramon.zhang/project/shell/test > sh getopts.sh -a hello
getopts test
the -a option is:
➜ /Users/ramon.zhang/project/shell/test > cat getopts.sh
#!/bin/bash
echo "getopts test"
while getopts a option
do
case $option
in
a)
echo "the -a option is: $OPTARG"
;;
\?)
;;
esac
done
去掉1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
那另外一点,如果有```:```的情况下,不传入参数,会发生什么,这里同样看例子:
```sh
➜ /Users/ramon.zhang/project/shell/test > sh getopts.sh -a
getopts test
getopts.sh: option requires an argument -- a
➜ /Users/ramon.zhang/project/shell/test > cat getopts.sh
#!/bin/bash
echo "getopts test"
while getopts a: option
do
case $option
in
a)
echo "the -a option is: $OPTARG"
;;
\?)
;;
esac
done
很明显的报错了,不过需求是多样的,可能有些时候我们确实不用传参数,这时候我们就可以在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```sh
➜ /Users/ramon.zhang/project/shell/test > sh getopts.sh -a hello -b hey -c world -d
getopts test
the -a option is: hello
the -b option is: hey
the -c option is: world
the -d option is:
➜ /Users/ramon.zhang/project/shell/test > cat getopts.sh
#!/bin/bash
echo "getopts test"
while getopts :a::b:c:d option
do
case $option
in
a)
echo "the -a option is: $OPTARG"
;;
b)
echo "the -b option is: $OPTARG"
;;
c)
echo "the -c option is: $OPTARG"
;;
d)
echo "the -d option is: $OPTARG"
;;
\?)
;;
esac
done
上面就是getopts的基础用法了,还有一个相似的但是比较老的命令getopt,他支持长选项,有兴趣的可以去了解,这里就不介绍了。