0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

bash でオプションを処理する関数を作る

Posted at

bash でオプションを処理する方法はググれば出てきますが、もう少し見やすいコードにならないものかと思って書いてみました。

コード

processOptions.sh
function processOptions(){
  tgt=$1  # ターゲットになるオプション
  shift
  opts=($@)  # 探索対象のオプション全体
  flag=0
  for i in ${!opts[@]}
  do
    if [[ "$tgt" =~ ${opts[$i]} ]]; then
      eval ${command[$i]}
      flag=1
      break
    fi
  done
  if [[ $flag -eq 0 ]]; then  # invalid option
    echo "invalid option $tgt"
  fi
}

while (( $# > 0 ))
do
  # 配列の順序を対応付けること
  short=(a b c)
  long=(
    "--optionA"
    "--optionB"
    "--optionC"
  )
  command=(
    "echo \"optionA found\""
    "echo \"optionB found\""
    "echo \"optionC found\""
  )
  if [[ "$1" =~ ^--.*  ]]; then  # ロングオプション
    processOptions $1 ${long[*]}
  elif [[ "$1" =~ ^-.* ]]; then  # ショートオプション
    processOptions $1 ${short[*]}
  elif [[ "$1" =~ .* ]]; then  # 引数
    echo "argument $1 found"  # 引数の時の処理
  fi
  shift
done

使い方

./processOptions.sh --optionA --optionB のように呼び出すと

optionA found
optionB found

のように出力が得られます。

また、./processOptions.sh -cba のようなショートオプションの使い方もできます。

optionC found
optionB found
optionA found

のように出力が得られます。

問題点

  • ./processOptions.sh --optionA--optionB のようにロングオプションをつなげて呼び出すと、未知のロングオプションとしてはじきたいところですが、--optionA--optionB の両方が与えられたものとして動作してしまいます。
  • ./processOptions.sh -abcx のように未知のオプションを既知のオプションに紛れ込ませた場合、未知のオプションを見つけてはじきたいところですが、無視されます。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?