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

シェルスクリプトでチェックボックス式の選択メニューを作る

$
0
0

shell-selection.gif

自分の作業を効率化するようなCLIのツールを作ることはよくあると思います.
探してもあまり情報が多くはなかったので,作りました.Bash環境で動くチェックボックスのシェルスクリプトです.

#!/bin/bash#メニュー
options[0]="option 1"
options[1]="option 2"
options[2]="option 3"
options[3]="option 4"
options[4]="option 5"#各メニューごとに挙動を記述するfunction DOIT {if[[${choices[0]}]];then
        echo"Option 1 selected"fi

    if[[${choices[1]}]];then
        echo"Option 2 selected"fi

    if[[${choices[2]}]];then
        echo"Option 3 selected"fi

    if[[${choices[3]}]];then
        echo"Option 4 selected"fi

    if[[${choices[4]}]];then
        echo"Option 5 selected"fi}

clear

#現在フォーカスしているメニューcurrent_line=0

#メニュー一覧を表示function MENU {echo"移動:[↑]or[↓], 選択:[SPACE], 決定:[ENTER]"for NUM in${!options[@]};do
        if[$NUM-eq$current_line];then
            echo-n">"else
            echo-n" "fi
        echo"[${choices[NUM]:-}]"":${options[NUM]}"done}#メニュー選択のループfunction SELECT_LOOP {while true;do
        while MENU &&IFS=read-r-n1-s SELECTION &&[[-n"$SELECTION"]];do
            if[[$SELECTION==$'\x1b']];then
                read-r-n2-s rest
                SELECTION+="$rest"fi  
            clear

            case$SELECTIONin$'\x1b\x5b\x41')#up arrowif[[$current_line-ne 0 ]];then
                        current_line=$(( current_line -1))else
                        current_line=$((${#options[@]}-1))fi;;$'\x1b\x5b\x42')#down arrowif[[$current_line-ne$((${#options[@]}-1))]];then
                        current_line=$(( current_line +1))else
                        current_line=0
                    fi;;$'\x20')#spaceif[["${choices[current_line]}"=="+"]];then
                        choices[current_line]=""else
                        choices[current_line]="+"fi;;esacdone

        read-p"選べた? [Y/n]" Answer
        case$Answerin''|[Yy]*)break;;;[Nn]*);;*)echo"YES or NOで答えてね";;esac
        clear
    done}

SELECT_LOOP
DOIT

https://gist.github.com/shinyaoguri/782adf1c6765dba0717745578aa9c85f

最初のDOITの関数に選ばれたらやりたいことを入れておけば選択式で処理を行わせることができます.

個人的には,簡単なPCの環境構築のスクリプトなどをこれを使っていたりします.

誰かの参考になれば幸いです.

※この記事は以前自分のブログに書いた物をこちらに引越しさせた記事になります.元の記事は削除しました.


Viewing all articles
Browse latest Browse all 2722

Trending Articles