https://www.cnblogs.com/yeungchie/
可以用 getopt,但我还是喜欢自己写这个过程,便于我控制更多细节。
下面要实现的效果是,从命令行参数中分析,给 $libName, $cellName, $viewName 三个变量赋值,
- 分别通过选项来定义:
--lib
,--cell
,--view
- 同时也可以支持短选项来定义:
-l
,-c
,-v
- 设置参数默认值, $libName, $cellName 默认值为
undef
, $viewName 默认值为layout
- 用
-h
或者--help
可以打印帮助内容
代码示例
#!/bin/bash
#--------------------------
Program : getOptTemplate.sh
Language : Bash
Author : YEUNGCHIE
Version : 2022.08.13
#--------------------------
function HelpDoc {
定义一个函数, 方便写 help 信息
cat <&2
exit 1
;;
*)
# 报错提示, 无效的 option
echo "Invalid option - '$1'" >&2
echo "Try -h or --help for more infomation." >&2
exit 1
;;
esac
shift
done
分析结束
cat < $libName
Cell Name --> $cellName
View Name --> $viewName
EOF
exit 0
功能演示
- 未定义参数的默认值
$ ./getOptTemplate.sh
Input arguments:
Library Name --> undef
Cell Name --> undef
View Name --> layout
- 长选项和短选项
$ ./getOptTemplate.sh --lib OC1231 -c demo -v schematic
Input arguments:
Library Name --> OC1231
Cell Name --> demo
View Name --> schematic
- 错误参数名的报错
$ ./getOptTemplate.sh -library OC1231
Invalid option - '-library'
Try -h or --help for more infomation.
- 打印 help
$ ./getOptTemplate.sh -h
Usage:
-l, --lib Library Name
-c, --cell Cell Name
-v, --view View Name
Original: https://www.cnblogs.com/yeungchie/p/16027490.html
Author: YEUNGCHIE
Title: [ Shell ] 用 while + case 实现 GetOptions 效果
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/619465/
转载文章受原作者版权保护。转载请注明原作者出处!