https://www.cnblogs.com/yeungchie/
可以用 getopt,但我还是喜欢自己写这个过程,便于我够控制更多细节。
下面要实现的效果是,从命令行参数中分析,给 $libName,$cellName,$viewName 三个变量赋值,
- 分别通过选项:
--lib
,--cell
,--view
来定义 - 同时也可以支持短选项:
-l
,-c
,-v
来定义 - 如果存在没有定义的参数,则 $ib,$cell 使用默认值
undef
,$view 默认值layout
- 用
-h
或者--help
可以打印帮助内容
code
#!/bin/bash
#--------------------------
# Program : getOptTemplate.sh
# Language : Bash
# Author : YEUNGCHIE
# Version : 2022.03.19
#--------------------------
function help {
# 定义一个函数, 写 help 信息
cat <&2
exit 1
;;
*)
# 报错提示, 未知的 option
echo "Invalid option - '$1'" >&2
echo "Try -h or --help for more infomation." >&2
exit 1
;;
esac
fi
# 把命令行接受的参数列表的元素往前移一位
shift
done
# 分析结束
if [[ ! -n $libName ]]; then libName=undef ; fi
if [[ ! -n $cellName ]]; then cellName=undef ; fi
if [[ ! -n $viewName ]]; then viewName=layout; fi
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