shell編程之選擇結構

    選擇結構可讓咱們提供一些斷定條件,依據斷定條件的斷定結果的不一樣,而執行不一樣的語句塊。從而實現改變程序的操做流。常見的有if-then語句。
php

    bash中的if語句運行在if行定義的命令。若是命令的退出狀態碼爲0,則執行then後面的全部命令。若是命令的退出狀態碼爲非0值,那麼then後面的命令將不會被執行。正則表達式

    bash中if語句有多種結構:shell

       單分支:
               if  條件;then
                      語句1
                      語句2
                      ......
               fi
              
       多分支:
               if  條件;then
                      語句1
                      語句2
                      ......
               else
                      語句1
                      語句2
                      ...... 
               fi
       嵌套1:
              if   條件;then
                      語句1
                      語句2
                      ......
              elif 條件;then
                      語句1
                      語句2
                      ......
              else
                      語句1
                      語句2
                      ......
              fi
              
       嵌套2:
                
                if  條件;then
                      語句1
                      語句2
                      ......
                      if  條件2;then
                            語句1
                            語句2
                            ...... 
                      else
                            語句1
                            語句2
                            ......
                      fi
               else
                      語句1
                      語句2
                      ......
                      if  條件2;then
                            語句1
                            語句2
                            ...... 
                      else
                            語句1
                            語句2
                            ......
                      fi 
               fi

     test命令:express

         test命令提供了一種檢測if-then語句中不一樣條件的方法。
            若是test命令中列出的條件評估值爲true,test命令以0退出狀態碼退出,
            若是條件爲false,那麼test命令以非0退出狀態碼退出。
            
         使用test命令有兩種方法:
                第一種方法:
                           if test condition;then
                                   語句1
                                   語句2
                                   .....
                           fi
                第二種方法:
                           if [ condition ];then  //注:括號和conditon之間必須有空格
                                   語句1          //注:if和括號之間也必須有空格
                                   語句2
                                   .....
                           fi

     常見的條件判斷類型:apache

           數值比較:
                   -eq               等於
                   -gt               大於
                   -lt               小於
                   -ge               大於等於
                   -le               小於等於
                   -ne               不等於
                   
                   腳本實例:
                            #!/bin/bash
                            #
                            var1=10
                            var2=11
                            
                            if [ $var1 -gt 5 ];then
                                 echo "The test value $var1 is greater than 5."
                            fi
                            
                            if [ $var1 -eq $var2 ];then
                                echo "The values are equal."
                            else
                                echo "The values are different."
                            fi
                   
                            執行結果:
                            [root@localhost ~]# chmod +x 21.sh 
                            [root@localhost ~]# ./21.sh 
                            The test value 10 is greater than 5.
                            The values are different.
                            
                            #!/bin/bash
                            #
                            var1=`echo "scale=4;10 / 3"| bc`
                            echo "The test value is $var1"
                            if [ $var1 -gt 3 ];then
                                echo "The result is larger than 3"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 24.sh 
                            [root@localhost ~]# ./24.sh 
                            The test value is 3.3333
                            ./24.sh: line 5: [: 3.3333: integer expression expected
                            
                            //看到了嗎?test命令只支持整數
                            //bash只能處理整數數字。使用bc時,只是欺騙bash將浮點值
                            做爲字符串存儲在一個變量中。
                            
        字符串比較:
                   =                 是否相等
                   !=                是否不等
                   <                 是否小於
                   >                 是否大於
                   -n str1           檢查str1的長度是否大於0  非空(true)  空(false)
                   -z str1           檢查str1的長度是否爲0    空(true)  非空(false) 
                   
                   腳本實例:
                             判斷當前用戶是否爲root
                            #!/bin/bash
                            #
                            testuser=root
                            if [ $USER = $testuser ]
                            then
                                echo "Welcome $testuser"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 25.sh 
                            [root@localhost ~]# whoami
                            root
                            [root@localhost ~]# ./25.sh 
                            Welcome root
                            
                            #!/bin/bash
                            #
                            testuser=baduser
                            if [ $USER != $testuser ];then
                                echo "This isn't $testuser"
                            else
                                echo "Welcome $testuser"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 26.sh 
                            [root@localhost ~]# whoami
                            root
                            [root@localhost ~]# ./26.sh 
                            This isn't baduser
                            
                            
                            #!/bin/bash
                            #
                            var1=baseball
                            var2=hockey
                            if [ $var1 \> $var2 ];then
                                echo "$var1 is greater than $var2"
                            else
                                echo "$var1 is less than $var2"
                            fi    
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 27.sh 
                            [root@localhost ~]# ./27.sh 
                            baseball is less than hockey
                            
                            注:字符的大小比較是比較的字符串的ASCII碼大小
                                >和<號須要轉義
                                
                            #!/bin/bash
                            #
                            var1=Testing
                            var2=testing
                            if [ $var1 \> $var2 ];then
                                echo "$var1 is greater than $var2"
                            else
                                echo "$var1 is less than $var2"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 28.sh 
                            [root@localhost ~]# ./28.sh 
                            Testing is less than testing
                            
                            判斷一個變量是否包含數據:
                            #!/bin/bash
                            #
                            var1=testing
                            var2=''
                            if [ -n $var1 ];then
                               echo "The string $var1 is not empty"
                            else
                               echo "The string $var1 is empty"
                            fi
                            
                            if [ -z $var2 ];then
                               echo "The string $var2 is empty"
                            else
                               echo "The string $var2 is not empty"
                            fi
                            
                            if [ -z $var3 ];then
                               echo "The string $var3 is empty"
                            else
                               echo "The string $var3 is not empty"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 30.sh
                            [root@localhost ~]# ./30.sh 
                            The string testing is not empty
                            The string  is empty
                            The string  is empty
                            
                            注:空變量和沒有初始化的變量可能會對shell腳本測試
                            產生災難性的影響。若是不肯定變量的內容,在數值比較
                            或者字符串比較中使用它以前,最好使用-n或者-z測試下
                            它是否有值。
                            
         文件比較:
                  -d file            檢查file是否存在而且是一個目錄
                  -e file            檢查file是否存在
                  -f file            檢查file是否存在而且是一個文件
                  -r file            檢查file是否存在而且可讀
                  -s file            檢查file是否存在而且不爲空
                  -w file            檢查file是否存在而且可寫
                  -x file            檢查file是否存在而且可執行
                  -O file            檢查file是否存在而且被當前用戶擁有
                  -G file            檢查file是否存在而且默認組是否爲當前用戶組
                  file1 -nt file2    檢查file1是否比file2新
                  file1 -ot file2    檢查file1是否比file2舊
                  
                  腳本實例:
                            判斷文件夾是否存在:
                            #!/bin/bash
                            #
                            if [ -d $HOME ];then
                                echo "Your HOME directory exists"
                                cd $HOME
                            else
                                echo "There's a problem with your HOME directory"
                            fi 
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 31.sh 
                            [root@localhost ~]# ./31.sh 
                            Your HOME directory exists
                            
                            若是沒法判斷是文件或文件夾,可使用-e來判斷
                            #!/bin/bash
                            #
                            if [ -e $HOME ];then
                                echo "OK on the directory,now let's check the file"
                                if [ -e $HOME/testing ];then
                                     echo "Appending date to existing file"
                                     date >>$HOME/testing
                                else
                                     echo "Creating new file"
                                     date >>$HOME/testing
                                fi
                            else
                                echo "Sorry,you don't have a HOME directory"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 32.sh 
                            [root@localhost ~]# ./32.sh 
                            OK on the directory,now let's check the file
                            Creating new file
                            [root@localhost ~]# cat testing
                            Thu Jun 12 11:39:26 PDT 2014
                            
                            -e既適用於文件也適用於目錄
                            -f只適用於文件
                            -d只適用於目錄
                            #!/bin/bash
                            #
                            if [ -e $HOME ];then
                                echo "The object exists,is it a file?"
                                if [ -f $HOME ];then
                                       echo "Yes,it's a file"
                                else 
                                       echo "No,it's not a file"
                                       if [ -f $HOME/.bash_history ];then
                                             echo "But this is a file"
                                       fi
                                fi
                            else
                                echo "Sorry,the object doesn't exists"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 33.sh 
                            [root@localhost ~]# ./33.sh 
                            The object exists,is it a file?
                            No,it's not a file
                            But this is a file
                            
                            在嘗試從文件中讀取數據以前,一般檢查是否可以讀取改文件
                            #!/bin/bash
                            #
                            pwfile=/etc/shadow
                            if [ -f $pwfile ];then
                                if [ -r $pwfile ];then
                                    tail $pwfile
                                else
                                    echo "Sorry,I'm unable to read the $pwfile file"
                                fi
                            else
                                echo "Sorry,the file $pwfile doesn't exist"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 34.sh 
                            [root@localhost ~]# ./34.sh 
                            ntp:!!:16203::::::
                            apache:!!:16203::::::
                            saslauth:!!:16203::::::
                            postfix:!!:16203::::::
                            pulse:!!:16203::::::
                            sshd:!!:16203::::::
                            tcpdump:!!:16203::::::
                            admin:$1$ThVHQoOH$mf66dh2AU.pZh1ky0olou1:16203:0:99999:7:::
                            student:!!:16229:0:99999:7:::
                            student1:!!:16229:0:99999:7:::
                            
                            判斷文件是否爲空
                            #!/bin/bash
                            #
                            file=t1test
                            touch $file
                            if [ -s $file ];then
                               echo "The $file exists and has data in it"
                            else
                               echo "The $file not exists or is empty"
                               date >>$file
                            fi
                            
                            if [ -s $file ];then
                               echo "The $file file has data in it"
                            else 
                               echo "The $file file is still empty"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 35.sh
                            [root@localhost ~]# ./35.sh 
                            The t1test not exists or is empty
                            The t1test file has data in it
                            
                            判斷文件是否可寫
                            #!/bin/bash
                            #
                            logfile=$HOME/t1test
                            touch $logfile
                            chmod u-w $logfile
                            now=`date +%Y%m%d-%H%M`
                            
                            if [ -w $logfile ];then
                                echo "The program run at: $now" >$logfile
                                echo "The first attemp successed"
                            else
                                echo "The first attemp failed"
                            fi
                            
                            chmod u+w $logfile
                            if [ -w $logfile ];then
                               echo "The program run at: $now" >$logfile
                               echo "The second attemp successed"
                            else
                               echo "The second attemp failed"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# ./36.sh 
                            The first attemp failed
                            The second attemp successed
                            
                            判斷文件是否能運行
                            #!/bin/bash
                            #
                            if [ -x 22.sh ];then
                               echo "You can run the script."
                               ./22.sh
                            else
                               echo "Sorry,you are unable to execute the script."
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 37.sh
                            [root@localhost ~]# ./37.sh 
                            You can run the script.
                            
                            判斷文件全部者是否爲當前用戶
                            #!/bin/bash
                            #
                            if [ -O /etc/passwd ];then
                                echo "You're the owner of the /etc/passwd file"
                            else
                                echo "You're not the owner of the /etc/passwd file"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# ./38.sh 
                            You're the owner of the /etc/passwd file
                            
                            判斷文件屬組是否與當前用戶的默認組相同
                            #!/bin/bash
                            #
                            if [ -G $HOME/testing ];then
                               echo "Same group"
                            else
                               echo "Not same group"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# ./39.sh 
                            Same group
                            
                            判斷文件新舊
                            #!/bin/bash
                            #
                            if [ ./22.sh -nt ./39.sh ];then
                               echo "22.sh new"
                            else
                               echo "39.sh new"
                            fi
                            
                            if [ ./22.sh -ot ./39.sh ];then
                               echo "22.sh old"
                            else
                               echo "39.sh old"
                            fi
                            
                            執行結果:
                            [root@localhost ~]# chmod +x 40.sh 
                            [root@localhost ~]# ./40.sh 
                            39.sh new
                            22.sh old
                            
                            注:-nt -ot 不能判斷文件是否存在
                               若是文件不存在則返回flase

複合條件檢查:
bash

           [ condition1 ] && [ condition2 ]
           兩個條件都知足則執行then的語句塊
           [ condition1 ] || [ condition2 ]
           兩個條件知足一個則執行then的語句塊
           
           例如:
                #!/bin/bash
                #
                if [ -d $HOME ] && [ -w $HOME/testing ];then
                   echo "The file exists and you can write to it"
                else
                   echo "I can't write to the file"
                fi 
                
                執行結果:
                [root@localhost ~]# chmod +x 41.sh 
                [root@localhost ~]# ./41.sh 
                The file exists and you can write to it

使用雙圓括號:less

             雙圓括號內可使用任何的數學賦值表達式或數學比較表達式。ssh

            例如:
                 #!/bin/bash
                 #
                 var1=10
                 if (($var1 ** 2 > 90));then
                   ((var2=$var1 ** 2))
                   echo "The square of $var1 is $var2"
                 fi
                 
                 執行結果:
                 [root@localhost ~]# ./42.sh 
                 The square of 10 is 100
                 
                 注:雙圓括號的特殊字符沒必要轉義
                     且字符和雙圓括號之間沒必要有空格

使用雙中括號:tcp

              能夠進行模式匹配:能夠定義與字符串匹配的正則表達式。ide

             例如:
                  #!/bin/bash
                  #
                  if [[ $USER == r* ]];then
                     echo "Hello $USER"
                  else
                     echo "Sorry,I don't know you"
                  fi
                  
                  執行結果:
                  [root@localhost ~]# ./43.sh 
                  Hello root
                  
                  注:雙中括號和字符之間必須有空格

case語句:

            實例:
                 #!/bin/bash
                 #
                 case $USER in
                 rich | root)
                         echo "Welcome,$USER"
                         echo "Please enjoy your visit";;
                 testing)
                         echo "Special testing account";;
                 *)
                         echo "Sorry,you're not allowed here";;
                 esac
                 
                 執行結果:
                 [root@localhost ~]# chmod +x 45.sh 
                 [root@localhost ~]# ./45.sh 
                 Welcome,root
                 Please enjoy your visit

練習題:

      1,判斷用戶是否存在,若是存在則說明其存在。
         #!/bin/bash
         #
         UserName=user1
         if id $UserName &> /dev/null;then
               echo "$UserName exists."
         fi
      2,若是用戶存在則打印其UID和SHELL。
         #!/bin/bash
         #
         UserName=user1
         if id $UserName &> /dev/null;then
               echo `grep "$UserName:" /etc/passwd | cut -d: -f1,3`
         fi 
      3,若是設備/dev/sda1已經掛載,就顯示其掛載點。
      4,若是/etc/rc.d/rc.sysinit中有空白行,就顯示其空白行行數。
      5,給定一個用戶,若是其ID號大於499,就說明其是普通用戶,
         不然,就說明是管理員或系統用戶。
      6,寫一個腳本,隨機生成一個整數,斷定,顯示其奇偶性:
      7,給定一個用戶,若是其UID等於GID,就說明這是個「good guy」不然「bad guy」 
      8,給定一個用戶,若是其uid爲0,就顯示此爲管理員  
         不然,就顯示其爲普通用戶
相關文章
相關標籤/搜索