項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【Bash 基本語法 #7】bash input options, 類似 argparse 的 bash script 實作範例程式碼

前言

getopts 寫 script 作為參數傳入好用,改天再來寫 getopt,
功能更強,但基本的 getopt 已經很好用了。

使用 getopts 來處理 input options 範本 (帶參數)

#!/bin/bash
optstr=":m:t:"
while getopts $optstr opt; do
  case $opt in
    m) mode=$OPTARG ;;
    t) target=$OPTARG ;;
    \?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
  esac
done

# check non zero
if [[ -z "$mode" ]]; then
  echo "Error: -m (mode) flag is required."
  exit 1
fi

if [[ -z "$target" ]]; then
  echo "Error: -t (target) flag is required."
  exit 1
fi

echo mode=$mode
echo target=$target

說明

getopts 是 bash 內建處理參數的工具
用法如上,而 optstr 就是表示有哪些短的選項 (options)

  • -z: 表示非零 (有存到東西),這邊多出來的實作就是必須要傳入參數。

使用 getopts 來處理 input options 範本 (不帶參數,純選項)

其實差別就只在有沒有跟一個冒號

範例程式碼

#!/bin/bash

function usage() {
cat <<EOF

This is a $0 options usage.

options:
    -h help
    -v verbose
EOF
}

VAR=0
while getopts "hv" OPTION
do
    case "$OPTION" in
        h) 
            usage
            exit;;
        v) 
            VAR=1;;
        ?)
            usage
            exit 1;;
    esac
done

結果

  • -h, -v 是有被我們設定的選項
  • ? 表示任意的其他選項
  • 沒給選項則不反應

說明

相比範例一,其實只要注意 optstr 的處理不同即可,
hv後面不帶「:」,表示是一個不存參數的選項

cat EOF

cat <<EOF
...
EOF

用於處理 multi-text

exit, exit 0, exit 1

另外 exit, exit 0, 預設是表示返回沒有異常的成功執行完 script

exit 1 通常會被使用於有例外狀況的時候,作為後續直行程式的判斷

使用位置變數 ($N) 來處理 input options 範本

#!/bin/bash

function usage() {
    cat <<EOF

Usage: $(basename "$0") [options]

Options:
    -a VALUE    Description for option a.
    -b VALUE    Description for option b.
    -c VALUE    Description for option c.
    -h, --help  Display this help and exit.
    --debug     Enable debug mode.

EOF
}

function parse_option() {
    if [ -n "$2" ]; then
        echo "$2"
    else
        echo "Error: Argument for $1 is missing" >&2
        usage
        exit 1
    fi
}

DEBUG=0

while [[ $# -gt 0 ]]; do
    case "$1" in
        -a)
            A=$(parse_option "$1" "$2")
            shift 2
            ;;
        -b)
            B=$(parse_option "$1" "$2")
            shift 2
            ;;
        -c)
            C=$(parse_option "$1" "$2")
            shift 2
            ;;
        -h|--help)
            usage
            exit
            ;;
        --debug) 
            DEBUG=1
            shift
            ;;
        --) # End of all options
            shift
            break
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            usage
            exit 1
            ;;
    esac
done

echo "A=$A, B=$B, C=$C"
echo "debug=$DEBUG"

說明

  • 「;;」: case 使用,表示結束一個特定的 case 分支
  • 「 $# -gt 0」:判斷還有沒有參數,搭配 while, gt = greater than, 因為還有 shift 的關係,因此此數字會慢慢減少到 0
  • 「-n $2」: n 為 non-zero, 判斷 $2 是否存在, 上面的例子就是必須存在 (不然 argparse 沒存東西)

Reference