选择结构可以让我们提供一些判定条件,依据判定条件的判定结果的不同,而执行不同的语句块。从而实现改变程序的操作流。常见的有if-then语句。

    bash中的if语句运行在if行定义的命令。如果命令的退出状态码为0,则执行then后面的所有命令。如果命令的退出状态码为非0值,那么then后面的命令将不会被执行。

    bash中if语句有多种结构:

       单分支:               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命令:

         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

     常见的条件判断类型:

           数值比较:                   -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

复合条件检查:

           [ 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

使用双圆括号:

             双圆括号内可以使用任何的数学赋值表达式或数学比较表达式。

            例如:                 #!/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                                  注:双圆括号的特殊字符不必转义                     且字符和双圆括号之间不必有空格

使用双中括号:

              可以进行模式匹配:可以定义与字符串匹配的正则表达式。

             例如:                  #!/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,就显示此为管理员           否则,就显示其为普通用户