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