歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux Shell腳本入門教程系列之(十四) Shell Select教程

Linux Shell腳本入門教程系列之(十四) Shell Select教程

日期:2017/3/3 12:02:38   编辑:SHELL編程
本文是Linux Shell腳本系列教程的第(十四)篇,更多Linux Shell教程請看:Linux Shell腳本系列教程
在上一篇文章:Linux Shell系列教程之(十三)Shell分支語句case … esac教程 的最後,我們簡單的介紹了一下使用case…esac來建立菜單的方法,其實shell中還有另外一種更專業的建立菜單的語句:select語句。
 
Select 搭配 case來使用,可以完成很多復雜的菜單控制選項。
select和其他流控制不一樣,在C這類編程語言中並沒有類似的語句,今天就為大家介紹下Shell Select語句的用法。

 

一、Shell Select語句語法

Shell中Select語句的語法如下所示:
select name   [in   list ] 
do 
    statements that can use  $name... 
done

 
說明:select首先會產生list列表中的菜單選項,然後執行下方do…done之間的語句。用戶選擇的菜單項會保存在$name變量中。
 
另外:select命令使用PS3提示符,默認為(#?);
在Select使用中,可以搭配PS3=’string’來設置提示字符串。

 

二、Shell Select語句的例子

還是老樣子,通過示例來學習Shell select的用法:
#!/bin/bash  
#Author:linuxdaxue.com
#Date:2016-05-30
#Desc:Shell select 練習
PS3='Please choose your number: ' # 設置提示符字串.  
echo
select number in "one" "two" "three" "four" "five"  
do  
echo  
echo "Your choose is $number."    
echo  
break  
done 
exit 0

 
說明:上面例子給用戶呈現了一個菜單讓用戶選擇,然後將用戶選擇的菜單項顯示出來。
這是一個最基本的例子,主要為大家展示了select的基礎用法。當然,你也可以將break去掉,讓程序一直循環下去。
 
下面是去掉break後輸出:
$./select.sh
1) one
2) two
3) three
4) four
5) five
Please choose your number: 1

Your choose is one.

Please choose your number: 2

Your choose is two.

Please choose your number: 3

Your choose is three.

Please choose your number: 4

Your choose is four.

Please choose your number: 5

Your choose is five.

 
然後我們將例子稍稍修改下,加入case…esac語句:
#!/bin/bash  
#Author:linuxdaxue.com
#Date:2016-05-30
#Desc:Shell select case 練習
PS3='Please choose your number: ' # 設置提示符字串.  
echo
select number in "one" "two" "three" "four" "five"  
do
case $number in
one )
echo Hello one!
;;
two )
echo Hello two!
;;
* )
echo  
echo "Your choose is $number."    
echo
;;
esac
#break  
done 
exit 0

 
這樣的話,case會對用戶的每一個選項進行處理,然後執行相應的語句。輸出如下:
$./select2.sh
1) one
2) two
3) three
4) four
5) five
Please choose your number: 1
Hello one!
Please choose your number: 2
Hello two!
Please choose your number: 3

Your choose is three.

Please choose your number: 4

Your choose is four.

 
將這些語句進行修改拓展,就可以寫出非常復雜的腳本。怎麼樣,是不是非常強大呢,趕快試試吧!
更多Linux Shell教程請看:Linux Shell腳本系列教程
 
原文:Linux Shell系列教程之(十四) Shell Select教程
上一篇:Linux Shell腳本入門教程系列之(十三)Shell分支語句case … esac教程
下一篇:Linux Shell腳本入門教程系列之(十五) Shell函數簡介
本文轉自:Linux Shell腳本入門教程系列之(十四) Shell Select教程
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Copyright © Linux教程網 All Rights Reserved