各位看官们,咱们今天还是接着上一回的内容,列举具体的例子给大家。闲话休说,言归正转。
看官们在编写程序的时候,可能会需要向用户提供一个选择菜单。怎么办?不用着急,咱们今天就来说说
如何编写选择菜单。
打开终端,新建立一个叫sample.sh的脚本文件,并且在终端中输入下面的内容,然后保存该文件:
#! /bin/bash echo "-----------------the starting line of shell-----------------" echo "please input the number for selecting country: 1. China 2. England 3. America 4. Russia 5. French 6. German" value=0; read -p "input: " value case $value in 1) echo "You select the China." ;; 2) echo "You select the England" ;; 3) echo "You select the America" ;; 4) echo "You select the Russia" ;; 5) echo "You select the French" ;; 6) echo "You select the German" ;; *) echo "You select number is not in the menu" exit 1 ;; esac echo "-----------------the ending line of shell-----------------"
在终端中执行命令:./sample.sh,提示Input时,输入数字1,可以得到以下结果:
-----------------the starting line of shell-----------------
please input the number for selecting country:
1. China
2. England
3. America
4. Russia
5. French
6. German
input: 1
You select the China.
-----------------the ending line of shell-----------------
如果输入的数字,不在1-6之间,则会得到下面的结果:
-----------------the starting line of shell-----------------
please input the number for selecting country:
1. China
2. England
3. America
4. Russia
5. French
6. German
input: 9
You select number is not in the menu
看官们,这就是一个选择菜单的例子,例子中首先提供一个菜单供用户选择,然后捕获用户输入的内容,
通过case语句来判断用户的输入的内容,并且依据输入的内容输出不同的结果。
例子中有一点需要注意,当用户输入的内容不在菜单中时,会提示错误并且退出程序。
各位看官们,今天的例子就到此为止,欲知后面还有什么好的例子,且听下回分解。