「シェルスクリプトの基礎 - select文」の版間の差分
ナビゲーションに移動
検索に移動
細 (文字列「</source>」を「</syntaxhighlight>」に置換) |
細 (文字列「__FORCETOC__」を「{{#seo: |title={{PAGENAME}} : Exploring Electronics and SUSE Linux | MochiuWiki |keywords=MochiuWiki,Mochiu,Wiki,Mochiu Wiki,Electric Circuit,Electric,pcb,Mathematics,AVR,TI,STMicro,AVR,ATmega,MSP430,STM,Arduino,Xilinx,FPGA,Verilog,HDL,PinePhone,Pine Phone,Raspberry,Raspberry Pi,C,C++,C#,Qt,Qml,MFC,Shell,Bash,Zsh,Fish,SUSE,SLE,Suse Enterprise,Suse Linux,openSUSE,open SUSE,Leap,Linux,uCLnux,Podman,電気回路,電子回路,基板,プリント基板 |description={{PAGENAME}} - 電子回路とSUSE Linuxに関する情報 | This pag…) |
||
| 88行目: | 88行目: | ||
Input number: 3 | Input number: 3 | ||
<br><br> | <br><br> | ||
{{#seo: | |||
|title={{PAGENAME}} : Exploring Electronics and SUSE Linux | MochiuWiki | |||
|keywords=MochiuWiki,Mochiu,Wiki,Mochiu Wiki,Electric Circuit,Electric,pcb,Mathematics,AVR,TI,STMicro,AVR,ATmega,MSP430,STM,Arduino,Xilinx,FPGA,Verilog,HDL,PinePhone,Pine Phone,Raspberry,Raspberry Pi,C,C++,C#,Qt,Qml,MFC,Shell,Bash,Zsh,Fish,SUSE,SLE,Suse Enterprise,Suse Linux,openSUSE,open SUSE,Leap,Linux,uCLnux,Podman,電気回路,電子回路,基板,プリント基板 | |||
|description={{PAGENAME}} - 電子回路とSUSE Linuxに関する情報 | This page is {{PAGENAME}} in our wiki about electronic circuits and SUSE Linux | |||
|image=/resources/assets/MochiuLogo_Single_Blue.png | |||
}} | |||
__FORCETOC__ | __FORCETOC__ | ||
[[カテゴリ:シェルスクリプト]] | [[カテゴリ:シェルスクリプト]] | ||
2024年10月14日 (月) 10:38時点における最新版
概要
select文を使用すると、簡易的な対話型メニューが簡単に作成できる。(繰り返し文 + メニュー表示機能のような処理)
実際には、メニューを表示して反復処理に入り、変数と分岐処理を使用して制御することが多い。
なお、select文はbashで追加された制御文であり、shには対応していない。
select文の書式
<文字列変数>="<選択を促す文字列>"
<配列変数>="<配列>"
select <変数> in <配列変数>
do
<変数に応じた処理>
done
select文のサンプル(1)
以下の例では、変数STRINGに代入した内容が、select文のところで標準出力されている。
#!/bin/bash
STRING="Input number: "
menu="apple orange banana finish"
select var in ${menu}
do
echo "You selected ${var}"
if [ ${var} = "finish" ]; then
exit 1
fi
done
echo "Finish script."
# 実行結果 1) apple 2) orange 3) banana 4) finish Input number: 1 You selected apple Input number: 2 You selected orange Input number: 3 You selected banana Input number: 4 You selected finish
select文のサンプル(2)
以下の例では、caseで処理を分岐およびコマンドを実行して、終了後にプロンプトを再表示するようにしている。
変数REPLYはselect文を使用する時に、内部で生成される特別な変数である。
この中には、ユーザが入力した値が代入される。(数字のほか文字列も表示される)
#!/usr/bin/bash
STRING="Input number: "
menu="pwd ls exit"
select VAR in ${menu}
do
# 反復処理の中でcase文を使用している
case $VAR in
"ls" ) ls -1 ;;
"pwd" ) pwd ;;
"exit" ) break ;;
* ) echo "あなたの入力した番号は$REPLYです"
esac
done
# 実行結果 1) pwd 2) ls 3) exit Input number: 1 /home/<ユーザ名>/SampleScripts Input number: 2 a.txt b.txt Input number: 4 あなたの入力した番号は4です Input number: 3