Select in statement in Shell
- select in usage
- The select in loop is used to enhance the interactivity. It can display numbered menus. The user can select different menus and perform different functions by entering different numbers.
- Select in is a unique loop of the shell, which is very suitable for interactive scenarios such as Terminal. This is not available in other languages.
usage:
select variable in value_list #variable表示变量,value_list表示取值列表
do
statements
done
1.#?用来提示用户输入菜单编号;^D表示按下Ctrl+D组合键,它的作用是结束select in循环
2.每次循环时,selevt都会要求用户输入菜单编号,并使用环境变量PS3的值作为提示符,PS3的默认值为#?,修改PS3的值就可以修改提示符
3.如果用户输入的菜单编号不在范围之内,那么就会给variable赋一个空值;如果用户输入一个空值,会重新显示一遍菜单
Example 1.
vim test.sh
#!/bin/bash
#test the usage of 'select in'.
echo "What is your favourite OS? "
select name in "Linux" "Windows" "Mac OS" "Unix" "Android" '//“ ”可以省略'
do
echo $name
done ##此处不会自动跳出select in 循环,需要按ctrl+D跳出select in
echo "You have selected $name"
run:
[root@server1 ~]# chmod u+x test.sh
[root@server1 ~]# ./test.sh
What is your favourite OS?
1) Linux
2) Windows
3) Mac OS
4) Unix
5) Android
#? 1
Linux
#? '//按ctrl+D'
You have selected Linux
=======================================================
[root@server1 ~]# ./test.sh
What is your favourite OS?
1) Linux
2) Windows
3) Mac OS
4) Unix
5) Android
#? 5
Android
#? 3
Mac OS
#? 2
Windows
#? '//按ctrl+D'
You have selected Windows
- select in is usually used with case in
Example 2:
#!/bin/bash
#"select in" is usually used with "case in"
echo "What is your favourite OS? "
select name in "Linux" "Windows" "Mac OS" "Unix" "Android"
do
case $name in
"Linux")
echo "Linux是一个类Unix操作系统,它开源免费"
break
;;
"Windows")
echo "Mac OS是微软开发的个人电脑操作系统,它是闭源收费的"
break
;;
"Mac OS")
echo "Mac OS是苹果公司开发的一款图形界面操作系统"
break
;;
"Unix")
echo "Unix是操作系统的开山鼻祖,现在只应用在一些特殊场合"
break
;;
"Android")
echo "Android是由Google开发的手机操作系统"
break
;;
*)
echo "没有这个选项!"
break
esac
done
run:
[root@server1 ~]# ./test2.sh
What is your favourite OS?
1) Linux
2) Windows
3) Mac OS
4) Unix
5) Android
#? 1
Linux是一个类Unix操作系统,它开源免费
[root@server1 ~]# ./test2.sh
What is your favourite OS?
1) Linux
2) Windows
3) Mac OS
4) Unix
5) Android
#? 2
Mac OS是微软开发的个人电脑操作系统,它是闭源收费的
[root@server1 ~]# ./test2.sh
What is your favourite OS?
1) Linux
2) Windows
3) Mac OS
4) Unix
5) Android
#? 5
Android是由Google开发的手机操作系统