Quantcast
Channel: Bashタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 2914

bashで複数選択のメニューを作る

$
0
0

検索してもあまり情報が出てこなかったので、自分用にメモ。

関数

multiple_select() {
  local PS3="$1(複数選択する場合は、半角スペースを開けてください)> "
  local items="$2 exit"
  local itemarray=($items)
  local itemlen=${#itemarray[@]}
  local regex='^[1-9][0-9]*$'
  local res=''

  select selection in $items; do
    for i in $REPLY; do
      if ! [[ $i =~ $regex && $i -le $itemlen ]]; then
        echo "入力値が不正です。" 1>&2
        return 1
      fi
      if [ $i -eq $itemlen ]; then
        echo ""
        return 0
      fi
      # 設定済みの場合は無視する
      if [[ $res == *"${itemarray[i-1]}"* ]]; then
        continue
      fi
      res+=" ${itemarray[i-1]}"
    done
    echo $res
    return 0
  done
}

使い方

my_favorite_fruits=`multiple_select \
  "好きな果物は何ですか?" \
  "りんご みかん いちご バナナ"` \
|| exit 1

出力

1) りんご
2) みかん
3) いちご
4) バナナ
5) exit
好きな果物は何ですか?(複数選択する場合は、半角スペースを開けてください)> 1 2 2 4 1 4 4
りんご みかん バナナ

1) りんご
2) みかん
3) いちご
4) バナナ
5) exit
好きな果物は何ですか?(複数選択する場合は、半角スペースを開けてください)> a
入力値が不正です。

Viewing all articles
Browse latest Browse all 2914

Trending Articles