shell getopts语法

Linux shell中getopts语法是一个很高级的语法,它能让你写出很漂亮的shell,来看个例子学习下

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
root@ubuntu:~# cat getopts.sh 
#!/bin/bash
# a: b: c: 表示脚本运行时接受选项<-a options_1> <-b options_2> <-c options_3>
# first: 表示友好, 给出错误选项时尽量少的打印错误信息
# OPTARG 表示选项给的值
# OPTIND 表示选项指针(下一位)
# 比如:(-a 指针为2) (-a a1 -b 指针为4) (-a a1 -b b1 -c c1指针为7)

while getopts ":a:b:c:" OPT;
do
case $OPT in
a)
echo "a is OPTARG: $OPTARG"
echo "a is OPTIND: $OPTIND"
;;
b)
echo "b is OPTARG: $OPTARG"
echo "b is OPTIND: $OPTIND"
;;
c)
echo "c is OPTARG: $OPTARG"
echo "c is OPTIND: $OPTIND"
;;
*)
echo "Usage: $0 [-a arg1] [-b arg2] [-c arg3]"
esac
done
shift $(($OPTIND-1))
echo "\$1 is: $1"
root@ubuntu:~# bash getopts.sh -a a1 -b b1 -c c1 test.sh
a is OPTARG: a1
a is OPTIND: 3
b is OPTARG: b1
b is OPTIND: 5
c is OPTARG: c1
c is OPTIND: 7
$1 is: test.sh