[ Shell ] 兩個 case 實現 GetOptions 效果

//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 <<EOF
Usage:
  -l, --lib     Library Name
  -c, --cell    Cell Name
  -v, --view    View Name
EOF
}

# 這裡開始分析輸入參數
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
    # 把命令行接受的參數列表的元素往前移一位
    shift
done
# 分析結束

if [[ ! -n $libName  ]]; then libName=undef  ; fi
if [[ ! -n $cellName ]]; then cellName=undef ; fi
if [[ ! -n $viewName ]]; then viewName=layout; fi

cat <<EOF
Input arguments:
Library Name --> $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
    
Tags: