27_Shell語言————case語句、bash如何與用戶進行交互(case、read)

1、case語句git

前面一直在用if語句實現選擇分支,if語句當然能夠完成多分支的條件判斷,但代碼不夠清晰簡潔,因此本章引入選擇分支的另外一種形式:case語句。該語句和if並沒有太大差異,主要做用是使代碼的邏輯結構更清晰。case語句的用法格式爲:正則表達式

 

case 變量引用(${}) invim

value1)bash

語句1app

語句2ide

...測試

;;ui

value2)spa

語句1rest

語句2

...

;;

value3)

語句1

語句2

...

;;

*)

語句1

語句2

...

;;

esac

 

下面來舉例演示case的用法:

 

1:寫一個腳本,能接受參數gzipbzip2xz,然後能將/etc/目錄歸檔備份至/backup目錄,並以參數指定的形式壓縮存放;文件名稱包含腳本執行時刻的時間


[root@localhost tutor]# vim compress_case.sh

 

#!/bin/bash
#
 
Com=$1
 
if [ -z $Com]; then
        Com=gzip
fi
 
[ -d /backup ]|| mkdir /backup
 
case $Com in
gzip)
        tar zcf /backup/etc-`date+%F-%H-%M-%S`.tar.gz /etc/*
        RetVal=$?
        ;;
bzip2)
        tar jcf /backup/etc-`date+%F-%H-%M-%S`.tar.bz2 /etc/*
        RetVal=$?
        ;;
xz)
        tar Jcf /backup/etc-`date+%F-%H-%M-%S`.tar.xz /etc/*
        RetVal=$?
        ;;
*)
# 這裏的 * 不是正則表達式,case中不支持正則表達式;可是case能夠使用 |,表示或者
        echo "Usage: `basename $0`{[gzip|bzip2|xz]}"
        exit 6
        ;;
esac
 
        [ $RetVal -eq 0 ] && echo"Backup etc finished.($Com)."

 

[root@localhost tutor]# ./compress_case.sh

tar: Removingleading `/' from member names
Backup etcfinished.(gzip).

[root@localhost tutor]# ls /backup

etc-2014-07-13-16-55-51.tar.gz

[root@localhost tutor]# ./compress_case.sh a

Usage:compress_case.sh {[gzip|bzip2|xz]}

[root@localhost tutor]# ./compress_case.sh xz

tar: Removingleading `/' from member names
Backup etcfinished.(xz).

[root@localhost tutor]# ls -hl /backup

total 15M
-rw-r--r--. 1root root 9.5M Jul 13 16:55 etc-2014-07-13-16-55-51.tar.gz
-rw-r--r--. 1root root 5.6M Jul 13 16:57 etc-2014-07-13-16-56-52.tar.xz

2. 前文中曾用if語句寫過一個SysV風格的服務腳本(26_Shell語言————if條件判斷之文件測試、短路操做符),該能夠接受一個參數,其使用形式以下:

          script.sh {start|stop|restart|status}

若是參數爲start,建立空文件/var/lock/subsys/script,並顯示「Starting scriptsuccessfully.」;

若是參數爲stop,則刪除文件/var/lock/subsys/script,並顯示「Stop script finished.」;

若是參數爲restart,則刪除文件/var/lock/subsys/script後從新建立,並顯示「Restarting scriptsuccessfully.」;

若是參數爲status,那麼:

          若是/var/lock/subsys/script文件存在,則顯示爲「script is running.

          不然,則顯示爲「script is stopped.

其它任何參數:則顯示「script.sh {start|stop|restart|status}

如今將if語句改爲case語句:

 

[root@localhost tutor]# vim service_case.sh

#!/bin/bash
#
 
SvcName=`basename$0`
LockFile=/var/lock/subsys/$SvcName
 
if [ $# -lt 1]; then
        echo "Usage: `basename $0`{start|restart|stop|status}"
        exit 5
fi
 
case $1 in
start)
        touch $LockFile
        echo "Starting $SvcNamefinished."
        ;;
stop)
        rm -f $LockFile
        echo "Stopping $SvcNamefinished."
        ;;
restart)
        rm -f $LockFile
        touch $LockFile
        echo "Restarting $SvcNamefinished."
        ;;
status)
        if [ -e $LockFile ]; then
                echo "$SvcName isrunning..."
        else
                echo "$SvcName isstoping..."
        fi
        ;;
*)
        echo "Usage: $SvcName {start|restart|stop|status}"
        exit 6
esac

 

[root@localhost tutor]# ./service_case.sh stat

Usage:service_case.sh {start|restart|stop|status}

[root@localhost tutor]# ./service_case.sh start

Startingservice_case.sh finished.

[root@localhost tutor]# ./service_case.sh restart

Restartingservice_case.sh finished.

[root@localhost tutor]# ./service_case.sh stop

Stoppingservice_case.sh finished.

[root@localhost tutor]# ./service_case.sh status

service_case.shis stoping...

 

2、bash如何與用戶進行交互

bash語言中有個內置命令read,能夠將用戶經過鍵盤輸入的內容保存到一個變量中。


[root@localhost tutor]# help read

read: read[-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-ttimeout] [-u fd] [name ...]

    Read a line from the standard input andsplit it into fields.

-p prompt output the string PROMPT without atrailing newline before attempting to read

# 指定提示信息

-t timeout time out and return failure if acomplete line of input is not read withint TIMEOUT seconds.

# 指定超時時間

 

[root@localhost tutor]# read Name

Mickey
# 將用戶輸入的Mickey保存到變量Name中

[root@localhost tutor]# echo $Name

Mickey

 

[root@localhost tutor]# read Name

Darius
# 從新輸入一個值,將爲該變量從新賦值

[root@localhost tutor]# echo $Name

Darius

 

[root@localhost tutor]# read A B

13 15
# read還能夠同時爲多個變量賦值

 

[root@localhost tutor]# echo $A

13

[root@localhost tutor]# echo $B

15

[root@localhost tutor]# read A B

13 15 17
# 變量和輸入的值的個數不一致


[root@localhost tutor]# echo $A

13

[root@localhost tutor]# echo $B

15 17
# 除了第一個值賦給了A,其他的都賦值給了B


[root@localhost tutor]# read A B

13
# 用戶輸入的值的個數小於變量的個數


[root@localhost tutor]# echo $A

13
# 只有變量A中有值,變量B爲空串

 

1. 寫一個腳本,來提示用戶輸入參數

 

[root@localhost tutor]# vim read.sh 

#!/bin/bash
 
echo -n"Please Select a Compress Method [gzip|bzip2|xz]:"
# -n選項表示顯示了echo的內容後不換行
read Com
echo $Com

[root@localhost tutor]# bash read.sh

Please Selecta Compress Method [gzip|bzip2|xz]:gzip
gzip

 

上述腳本中使用了echo的方法來提示用戶輸入參數,事實上read加上選項-p,自己就能夠給用戶以提示信息,故修改上述腳本:

 

[root@localhost tutor]# vim read.sh

#!/bin/bash
 
read -p"Please Select a Compress Method [gzip|bzip2|xz]:"  Com
# -p後面引號中的內容都會直接打印到屏幕上
echo $Com

 

[root@localhost tutor]# bash read.sh

Please Selecta Compress Method [gzip|bzip2|xz]:bzip2
bzip2

 

若是使用-t選項,還能夠設定輸入的超時時間:

[root@localhost tutor]# vim read.sh

#!/bin/bash
 
read -t 5 -p"Please Select a Compress Method [gzip|bzip2|xz]:"  Com
# 使用-t選項,設定超時時間爲5秒
echo $Com

[root@localhost tutor]# bash read.sh

PleaseSelect a Compress Method [gzip|bzip2|xz]:     
# 用戶一直沒有輸入,超時後顯示爲空


[root@localhost tutor]#

 

能夠採用if判斷語句,來爲空值的狀況設定默認值:

[root@localhost tutor]# vim read.sh

#!/bin/bash
 
read -t 5 -p"Please Select a Compress Method [gzip|bzip2|xz]:"  Com
[ -z $Com ]&& Com=gzip
# 若是用戶沒有輸入值,則默認值選擇gzip
echo $Com

 

[root@localhost tutor]# bash read.sh

Please Selecta Compress Method [gzip|bzip2|xz]:gzip
# 這裏gzip沒有換行,由於-p選項默認是不換行的

 

2. 寫一個腳本,判斷用戶輸入的是哪一種字符 

 

[root@localhost tutor]# vim user_input.sh

#!/bin/bash
#
read -p"Input a Character: " Char
 
case $Char in
[0-9])
        echo "A digit."
        ;;
[[:lower:]])
        echo "A lower."
        ;;
[[:upper:]])
        echo "An upper."
        ;;
[[:punct:]])
        echo "A punction."
        ;;
*)
        echo "Special Character."
esac

 

[root@localhost tutor]# chmod +x user_input.sh


[root@localhost tutor]# ./user_input.sh

Input aCharacter: 2
A digit.

[root@localhost tutor]# ./user_input.sh

Input aCharacter: a
A lower.

[root@localhost tutor]# ./user_input.sh

Input aCharacter: A
A lower.

[root@localhost tutor]# ./user_input.sh

Input aCharacter: ,
A punction.

[root@localhost tutor]# ./user_input.sh

Input aCharacter: ^[
SpecialCharacter.

 

3. 寫一個腳本,提示用戶是否接受協議

 

[root@localhost tutor]# vim agree.sh

#!/bin/bash
#
 
read -p"Do you agree: [Yes|No]:" YesNo
 
case $YesNo in
 
y|Y|[yY][eE][sS])
        echo "Agreed, proceed...";;
n|N|[nN][oO])
        echo "Disagreed,intterupt.";;
*)
        echo "Invalid input."
esac

[root@localhost tutor]# ./agree.sh

Do you agree:[Yes|No]:yes
Agreed,proceed...

[root@localhost tutor]# ./agree.sh

Do you agree:[Yes|No]:n
Disagreed,intterupt.

[root@localhost tutor]# ./agree.sh

Do you agree:[Yes|No]:a
Invalid input.

 

4. 顯示以下菜單,

1、顯示以下菜單給用戶:

m|M) showmemory usages;

d|D) showdisk usages;

q|Q) quit

2、若是用戶選擇了第一項,則顯示內存使用信息;若是選擇了第二項,則顯示磁盤掛載及使用相關信息;

   若是是第三項,退出,並顯示選擇退出;其它任何內容,均說明錯誤選項;

 

[root@localhost tutor]# vim show_menu.sh

 

cat <<EOF
 
m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
EOF
 
read -p"Your choice: " Choice
 
case $Choicein
m|M)
        free -m ;;
d|D)
        df -lh ;;
q|Q)
        echo "Quit..."
        exit 0 ;;
*)
        echo "Invalid input."
        exit 5
esac

 

 

[root@localhost tutor]# chmod +x show_menu.sh


[root@localhost tutor]# ./show_menu.sh 

m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: m
             total       used       free    shared    buffers     cached
Mem:           996        828        167          0        100        411
-/+ buffers/cache:        316        679
Swap:         2215          0       2215


[root@localhost tutor]# ./show_menu.sh

m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: D
Filesystem                    Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root   23G 4.5G   17G  22% /
tmpfs                         499M  120K 499M   1% /dev/shm
/dev/sda1                     485M   35M 426M   8% /boot
/dev/sdb3                     9.9G   36M 9.7G   1% /mydata
/dev/sr0                      288K 288K     0 100%/media/20140715_2041

[root@localhost tutor]# ./show_menu.sh

m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: Q
Quit...

[root@localhost tutor]# ./show_menu.sh

m|M showmemory usages;
d|D show diskusages;
q|Q quit
 
Your choice: a
Invalid input.
相關文章
相關標籤/搜索