Shell getopts处理多命令行选项

场景一:有多选项,但每次只用一个选项

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
#!/bin/bash
status=off #定义变量status,初始值设置为off
filename="" #定义变量filename,用于保存选项参数(文件)
output="" #定义变量output,用于保存选项参数(目录)

Usage () { #定义函数Usage,输出脚本使用方法
echo "Usage"
echo "myscript [-h] [-v] [-f <filename>] [-o <filename>]"
exit -1
}

while getopts :hvf:o: varname #告诉getopts此脚本有-h、-v、-f、-o四个选项,-f和-o后面需要跟参数

#没有选项时,getopts会设置一个退出状态FALSE,退出循环

do
case $varname in
h)
echo "$varname"
Usage
exit
;;
v)
echo "$varname"
status=on
echo "$status"
exit
;;
f)
echo "$varname"
echo "$OPTARG"
filename=$OPTARG #将选项的参数赋值给filename
if [ ! -f $filename ];then #判断选项所跟的参数是否存在且是文件
echo "the source file $filename not exist!"
exit
fi
;;
o)
echo "$varname"
echo "$OPTARG"
output=$OPTARG #将选项参数赋值给output
if [ ! -d $output ];then #判断选项参数是否存在且是目录
echo "the output path $output not exist"
exit
fi
;;
:) #当选项后面没有参数时,varname的值被设置为(:),OPTARG的值被设置为选项本身
echo "$varname"
echo "the option -$OPTARG require an arguement" #提示用户此选项后面需要一个参数
exit 1
;;
?) #当选项不匹配时,varname的值被设置为(?),OPTARG的值被设置为选项本身
echo "$varname"
echo "Invaild option: -$OPTARG" #提示用户此选项无效
Usage
exit 2
;;
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/bin/bash

while getopts "c:t:p:e:" opt_name; do
case $opt_name in
c)
case $OPTARG in
aws)
export cloud='aws'
;;
azure)
export cloud='azure'
;;
aliyun)
export cloud='aliyun'
;;
*)
echo "-c Option choose: aws, azure, aliyun"
exit 1
;;
esac
;;
t)
case $OPTARG in
one)
export clustertype='one'
;;
two)
export clustertype='two'
;;
*)
echo "-t Option choose: aaaa, bbbb"
exit 1
;;
esac
;;
p)
export project_name=$OPTARG
;;
e)
export project_env=$OPTARG
;;
:)
echo "$OPTARG Option need a argument"
;;
esac
done

echo "\033[31mAttention\!\033[0m" # red font
echo "Input parametes is: $cloud--$clustertype--$project_name--$project_env"

getopts、getopt的区别

在介绍如何使用getopts、getopt处理命令行参数之前,先来简单的说下getopt、getopts两者的各种特点和区别

首先来说getopts,getopts是shell中内建的命令,它的使用语法相对getopt简单,但它不支持长命令参数(–option)。它不会重排列所有参数的顺序,选项参数的格式必须是-d val,而不能是中间没有空格的-dval,遇到非-开头的参数,或者选项参数结束标记–就中止了,如果中间遇到非选项的命令行参数,后面的选项参数就都取不到了,出现的目的仅仅是为了代替getopt较快捷方便的执行参数的分析。

相反的是,getopts的缺点正好是getopt所具有的优点。相对于getopts而言,getopt是一个独立的外部工具(Linux的一个命令),它的使用语法比较复杂,支持长命令参数,会重排参数的顺序。在shell中处理命令行参数时,需要配合其他Linux命令一起使用才行。

总的来说getopts和getopt相比,getopts使用起来比较简单,但只支持短参数,getopt使用起来虽比较复杂,但处理的参数类型比较广泛


reference links:

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~