bash/引数

August 03, 2021

bash によるオプション解析 - Qiita

テンプレート、get_blocklist()関数、get_mac_addresslist()関数、ヘルプを表示する usage_exit()関数は用意してあるものとする

if [ $# -eq 0 ]; then
  get_blocklist
  exit
fi

while getopts bmh OPT
do
    case $OPT in
        b)  get_blocklist
            hoge="hogehoge"
            ;;
        m)  get_mac_addresslist
            ;;
        h)  usage_exit
            ;;
        \?) usage_exit
            ;;
    esac
done

shift $((OPTIND - 1))

最後の shift $((OPTIND - 1)) だが、これはコマンドライン中のオプションの部分を削除する動作

注意点

getopts コマンドでオプションを使ったシェルプログラミングは楽しい ♪

souce などで呼ぶと変数領域がそのまま引き継がれる様子。 個人的には bash だと全部グローバル変数なので、変数は汚染されやすいよな、と思う

引数処理

(1) case 文を使う.

while [ -n "$1" ]; do
case "$1" in
    -with-arg) shift; arg=$1; shift;;
    -no-arg)   shift;;
    *)         shift;;
    esac
    done

(2) getopts という getopt(3)みたいな./builtin もある.

    while getopts "n:" args $*; do
    if [ "$args" = "n" ]; then
foo=$OPTARG
fi
done

(3) 引数の個数のチェック

if [ $# -eq 1 ];then
date=$1
fi

Profile picture

Written by tin-machine 技術関連のメモ Twitter