https://www.cnblogs.com/yeungchie/
可以用 getopt,但我还是喜欢自己写这个过程,便于我控制更多细节。
下面要实现的效果是,从命令行参数中分析,给 $libName,$cellName,$viewName 三个变量赋值,
- 分别通过选项来定义:
--lib,--cell,--view - 同时也可以支持短选项来定义:
-l,-c,-v - 设置参数默认值,$libName,$cellName 默认值为
undef,$viewName 默认值为layout - 用
-h或者--help可以打印帮助内容
code
复制代码
- 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
bash
#--------------------------
# Program : getOptTemplate.sh
# Language : Bash
# Author : YEUNGCHIE
# Version : 2022.03.19
#--------------------------
function HelpDoc {
# 定义一个函数, 方便写 help 信息
cat <<EOF
Usage:
-l, --lib Library Name
-c, --cell Cell Name
-v, --view View Name
EOF
}
# 设置默认值
libName=undef
cellName=undef
viewName=layout
# 这里开始分析输入参数
while [[ -n $1 ]]; do
if [[ -n $opt ]]; then
case $opt in
# 根据 opt 来决定给什么变量赋值
lib_opt) libName=$1 ;;
cell_opt) cellName=$1 ;;
view_opt) viewName=$1 ;;
esac
# 赋值完了把 opt 复原
unset opt
else
case $1 in
# -短选项|--长选项) opt='起个名字' ;;
-l|--lib) opt='lib_opt' ;;
-c|--cell) opt='cell_opt' ;;
-v|--view) opt='view_opt' ;;
-h|--help)
# 打印 help 后退出
HelpDoc >&2
exit 1
;;
*)
# 报错提示, 无效的 option
echo "Invalid option - '$1'" >&2
echo "Try -h or --help for more infomation." >&2
exit 1
;;
esac
fi
# 把命令行接受的参数列表的元素往前移一位
shift
done
# 分析结束
cat <<EOF
Input arguments:
Library Name --> $libName
Cell Name --> $cellName
View Name --> $viewName
EOF
exit 0
演示
-
未定义参数的默认值
复制代码- 1
- 2
- 3
- 4
- 5
bash$ ./getOptTemplate.sh Input arguments: Library Name --> undef Cell Name --> undef View Name --> layout -
长选项和短选项
复制代码- 1
- 2
- 3
- 4
- 5
bash$ ./getOptTemplate.sh --lib OC1231 -c demo -v schematic Input arguments: Library Name --> OC1231 Cell Name --> demo View Name --> schematic -
错误参数名的报错
复制代码- 1
- 2
- 3
bash$ ./getOptTemplate.sh -library OC1231 Invalid option - '-library' Try -h or --help for more infomation. -
打印 help
复制代码- 1
- 2
- 3
- 4
- 5
bash$ ./getOptTemplate.sh -h Usage: -l, --lib Library Name -c, --cell Cell Name -v, --view View Name