25_Shell語言————if條件判斷之組合判斷(與、或、非)和多分支if語句

1、組合條件判斷ubuntu

組合條件測試是指能夠將多個條件組合起來進行判斷,條件和條件之間有邏輯關係。例如判斷一個數是否大於3,而且小於9,這裏大於3是一個條件,小於9也是一個條件,這兩個條件必須同時知足。同時知足即爲邏輯關係。一般邏輯關係有如下幾種:vim

與:-a,當指定多個條件時,默認爲與關係centos

或:-obash

非:!,這是個單目操做符編輯器

 

如判斷一個UID是否大於1,且小於499的寫法以下ide

[root@localhost tutor]# Uid=300測試

[root@localhost tutor]# [ $Uid -ge 1 ]ui

[root@localhost tutor]# echo $?spa

0

[root@localhost tutor]# [ $Uid -le 499 ]ip

[root@localhost tutor]# echo $?

0

[root@localhost tutor]# [ $Uid -ge 1 -a $Uid -le 499 ]

# 使用-a表示兩個與關係的條件,必須同時知足

[root@localhost tutor]# echo $?

0

[root@localhost tutor]# Uid=3000

[root@localhost tutor]# [ $Uid -ge 1 -a $Uid -le 499 ]

[root@localhost tutor]# echo $?

1

如判斷一個UID是否等於0,或者大於的寫法以下

[root@localhost tutor]# Uid=300

[root@localhost tutor]# [ $Uid -eq 0 -o $Uid -ge 500 ]

# 使用-o表示兩個或關係的條件,只須要知足其一便可

[root@localhost tutor]# echo $?

1

[root@localhost tutor]# Uid=3000

[root@localhost tutor]# [ $Uid -eq 0 -o $Uid -ge 500 ]

[root@localhost tutor]# echo $?

0

判斷一個UID是否不等於0,寫法以下:

[root@localhost tutor]# Uid=0

[root@localhost tutor]# [ ! $Uid -eq 0 ]

# 使用! 表示取反,這裏對Uid等於0的判斷結果進行取反,即爲Uid不等於0

[root@localhost tutor]# echo $?

1

[root@localhost tutor]# [ $Uid -ne 0 ]

# 這裏判斷Uid是否不等於0

[root@localhost tutor]# echo $?

1

 

. 寫一個腳本,經過參數傳遞一個字符串給腳本,若是傳遞的字符串爲「memory」或「Memory」,就以MB爲單位顯示當前主機的內存信息;不然,就顯示/proc/uptime文件的內容。

[root@localhost tutor]# vim memory1.sh

#!/bin/bash
if [ $1 =="memory" -o $1 == "Memory" ]; then
# 這裏再也不使用模式匹配了,而採用-o或關係來進行組合條件判斷
        free -m
else
        cat /proc/uptime
fi

[root@localhost tutor]# bash -x memory1.sh memory

+ '[' memory== memory -o memory == Memory ']'
+ free -m
             total       used       free    shared    buffers     cached
Mem:           996        511        484         0         57        160
-/+buffers/cache:        293        702
Swap:         2015          0       2015

[root@localhost tutor]# bash -x memory1.sh Memory

+ '[' Memory== memory -o Memory == Memory ']'
+ free -m
             total       used       free    shared    buffers     cached
Mem:           996        511        484        0         57        160
-/+buffers/cache:        293        702
Swap:         2015          0       2015

[root@localhost tutor]# bash -x memory1.sh abc

+ '[' abc ==memory -o abc == Memory ']'
+ cat/proc/uptime
50889.6250151.85

 

上面的邏輯關係,是針對條件組合的狀況,兩個或多個命令的運行結果也能夠組合判斷,其邏輯關係有以下幾種:

&&:

||:或

!:

寫一腳本,給定用戶,若是UID等於GID,就顯示爲「Good Guy」,不然顯示爲「BadGuy」若是其不存在,就退出腳本。

[root@localhost tutor]# vim if_user_lg.sh

#!/bin/bash
 
if ! id $1&> /dev/null; then
# 過去使用雙分支if來判斷不存在的狀況,這裏使用!表示判斷命令是否執行不成功
        echo "No such user."
        exit 6
fi
 
if [ `id -u$1` -eq `id -g $1` ]; then
        echo "Good Guy"
else
        echo "Bad Guy"
fi

[root@localhost tutor]# bash -x if_user_lg.sh root

+ id root
++ id -u root
++ id -g root
+ '[' 0 -eq 0']'
+ echo 'GoodGuy'
Good Guy

[root@localhost tutor]# echo $?

0

[root@localhost tutor]# bash -x if_user_lg.sh roott

+ id roott
+ echo 'Nosuch user.'
No such user.
+ exit 6

[root@localhost tutor]# echo $?

6

 

2、多分支if語句

前文中涉及到的條件判斷語句,只有單分支和雙分支的狀況,事實上bash也支持多分支的條件判斷,多分支的if語句是對雙分支if語句的擴展。多分支if語句提供多個if條件,但僅執行其中一個語句,其語法格式爲:

if 條件1; then

語句1

語句2

...

elif 條件2; then

語句1

語句2

...

elif 條件3; then

語句1

語句2

...

else

語句1

語句2

...

fi

 

下面來舉例演示多分支條件語句的使用方法:

 

1. 寫一個腳本:判斷當前主機的CPU生產商,其信息在/proc/cpuinfo文件中vendor id一行中。若是其生產商爲GenuineIntel,就顯示其爲Intel公司;若是其生產商爲AuthenticAMD,就顯示其爲AMD公司;

不然,就顯示沒法識別

 

[root@localhost tutor]# vim if_cpu1.sh

#!/bin/bash
#
Vendor=`grep"vendor_id" /proc/cpuinfo | uniq | cut -d: -f2`
 
if [[ $Vendor=~ [[:space:]]*GenuineIntel$ ]]; then
        echo "intel"
elif [[$Vendor =~ [[:space:]]*AuthenticAMD$ ]]; then
# 使用了elif進一步判斷是否爲AMD
        echo "AMD"
else
        echo "Unknown"
fi

 

[root@localhost tutor]# bash -x if_cpu1.sh

++ cut -d: -f2
++ uniq
++ grepvendor_id /proc/cpuinfo
+ Vendor='GenuineIntel'
+ [[  GenuineIntel =~ [[:space:]]*GenuineIntel$ ]]
+ echo intel
intel

 

2. 經過參數傳遞給腳本一個字符串,如Fedora,Gentoo, Redhat,判斷Linux發行版所處理主流發行系列:若是爲fedora,centos, redhat,就顯示RedHat;若是爲suse, opensuse,就顯示爲SUSE; 若是爲ubuntu, mint,  debian,就顯示爲Debian;不然,顯示爲其它

 

[root@localhost tutor]# vim version.sh

#!/bin/bash
#
if [ $1 =="fedora" -o $1 == "centos" -o $1 == "redhat" ];then
        echo "RedHat"
elif [ $1 =="suse" -o $1 == "opensuse" ]; then
        echo "SUSE"
elif [ $1 =="ubuntu" -o $1 == "mint" -o $1 == "debian" ];then
        echo "Debian"
else
        echo "Others"
fi

[root@localhost tutor]# bash version.sh redhat

RedHat

[root@localhost tutor]# bash version.sh mint

Debian

[root@localhost tutor]# bash version.sh opensuse

SUSE

[root@localhost tutor]# bash version.sh abc

Others

 

3. 寫一個能用來建立其餘腳本的腳本該腳本必須接受三個參數,最後一個參數爲文件名,但參數可變化,形如:

          script.sh  -a abc /u01/scripts/test1.sh

          script.sh  -d 2013-07-19 /u01/scripts/test1.sh

          script.sh  -D 'some infomation'  /u01/scripts/test1.sh

此腳本可以建立/u01/scripts/test1.sh文件,而且,若是給出了-a abc,則文件前兩行爲:

#!/bin/bash

# Author:abc

若是給出了-d 2014-07-23,則文件前兩行爲:

#!/bin/bash

# Date: 2013-07-23

若是給出了-D "someinfomation",則文件前兩行爲:

#!/bin/bash

#Description: some infomation

其它任何參數,均提示錯誤並退出

 

如下爲該腳本的初版:

——————————————————————————————————

[root@localhost ~]# vim mkscript

#!/bin/bash
#
if [ $# -ne 3]; then
        echo "the number of arguements iswrong."
        exit 4
fi
 # 判斷是否傳遞了3個參數
 
echo'#!/bin/bash' >> $3
     # 建立腳本,該腳本以第三個參數爲文件名,並將」#!/bin/bash」寫入腳本的第一行
 
if [ $1 =='-a' ]; then
        echo "# Author: $2" >>$3
# 若是第一個參數爲 -a,則將第二個參數做爲做者,寫入腳本的第二行
elif [ $1 =='-d' ]; then
        echo "# Date: $2" >> $3
# 若是第一個參數爲 -d,則將第二個參數做爲時間,寫入腳本的第二行
elif [ $1 =='-D' ]; then
        echo "# Description: $2">> $3
# 若是第一個參數爲 -D,則將第二個參數做爲描述,寫入腳本的第二行
else
        echo "Unkown Option, ignoreit."
        rm -f $3
 # 因爲已經建立了$3這個文件,且往文件中寫入了內容,故若是參數傳遞錯誤,應先刪除文件
 exit 5
fi
 
vim + $3
# 若是腳本可以被建立,則用vim打開腳本,當用戶在vim編輯器中完成編輯並保存以後,
# 會返回到當前的腳本,接着執行下面的語句
if bash -n $3> /dev/null; then
# 用戶編寫完 $3這個文件後判斷腳本是否有語法錯誤,若沒有則添加執行權限
        chmod +x $3
else
        echo "Sytax wrong in $3."
# 若是有語法錯誤,則提示用戶
fi

——————————————————————————————————

腳本到這裏就編寫完成了,下面執行該腳本以檢驗其是否完成了須要的功能

[root@localhost ~]# chmod +x mkscript

[root@localhost ~]# bash -n mkscript

[root@localhost ~]# ./mkscript /tmp/a.sh

the number ofarguements is wrong.
# 只傳遞了一個參數,故腳本中斷執行


[root@localhost ~]# ./mkscript -a mickey /tmp/a.sh

# 傳遞3個參數,腳本可以成功執行

[root@localhost ~]# cat /tmp/a.sh

#!/bin/bash
# Author:mickey
# 腳本/tmp/a.sh已經自動添加了兩行內容


[root@localhost ~]# ./mkscript -d 2014-07-24 /tmp/b.sh

[root@localhost ~]# cat /tmp/b.sh

#!/bin/bash
# Date:2014-07-24

[root@localhost ~]# ./mkscript -D "Toy Program"/tmp/c.sh

[root@localhost ~]# cat /tmp/c.sh

#!/bin/bash
# Description:Toy Program

[root@localhost ~]# ./mkscript -m hello /tmp/d.sh

Unkown Option,ignore it.
# 故意傳遞錯誤參數,以檢驗文件是否會被建立


[root@localhost ~]# ls /tmp

a.sh c.shkeyring-Xi9NCS  orbit-gdm  pulse-uP5T8Y6V6nIN  virtual-root.nBhtJw virtual-root.q9Sgpu  yum.log
b.sh keyring-bgxXAq keyring-xva5ss  orbit-root  pulse-yCmeAwocSW1U  virtual-root.plTHoO  irtual-root.rQ0Eab
# 沒有看到 /tmp/d.sh這個文件,說明它已經被刪除了


[root@localhost ~]# ./mkscript -a mickey /tmp/a.sh

#!/bin/bash
# Author:hello
~                                                                                                                             
~
# 若是參數都傳遞正確,則會自動打開腳本讓用戶編寫

[root@localhost ~]# ./mkscript -D "Syntax test"/tmp/e.sh

#!/bin/bash
# Description:Syntax test
 
if [ $1 -eq 0]; then
        echo Hello
 
~                                                                                                                             
~                                                                                                                              
# 故意不寫fi,來檢測該腳本中的語法檢查功能是否實現了。
/tmp/e.sh:line 7: syntax error: unexpected end of file
Sytax wrong in/tmp/e.sh.

[root@localhost ~]# ./mkscript -D "Syntax right"/tmp/f.sh

#!/bin/bash
# Description:Syntax right
if [ $1 -eq 0]; then
        echo hello
else
        echo world
fi
# 此次建立一個正確的腳本,用來檢查是否給該腳本添加了執行權限


[root@localhost ~]# ls -l /tmp/f.sh

-rwxr-xr-x. 1 root root 94 Jul 12 07:40 /tmp/f.sh
# 能夠看到f.sh這個文件已經有執行權限了


[root@localhost ~]# /tmp/f.sh 0

hello
# 能夠直接執行/tmp/f.sh這個腳本,爲其傳遞參數0
相關文章
相關標籤/搜索