乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Bash腳本編程學(xué)習(xí)筆記06:條件結(jié)構(gòu)體

       頭號碼甲 2022-07-24 發(fā)布于北京

      簡介

      在bash腳本編程中,條件結(jié)構(gòu)體使用if語句和case語句兩種句式。

      if語句

      單分支if語句

      if TEST; then
          CMD
      fi

      TEST:條件判斷,多數(shù)情況下可使用test命令來實(shí)現(xiàn),返回值為0的話則執(zhí)行CMD,否則就離開該條件結(jié)構(gòu)體,腳本繼續(xù)往下執(zhí)行。

      [root@c7-server ~]# cat test.sh
      #!/bin/bash
      if id zwl &> /dev/null; then
          echo "User zwl exists."
      fi
      [root@c7-server ~]# bash test.sh 
      User zwl exists.

      雙分支if語句

      if TEST; then
        
      CMD-TRUE else
        
      CMD-FALSE fi

      為真執(zhí)行CMD-TRUE,為假執(zhí)行CMD-FALSE。

      [root@c7-server ~]# cat test.sh
      #!/bin/bash
      read -p "Pleas input a user name:" name
      if id $name &> /dev/null; then
          echo "User $name exists."
      else
          echo "User $name doesn't exists."
      fi
      [root@c7-server ~]# bash test.sh 
      Pleas input a user name:zwl
      User zwl exists.
      [root@c7-server ~]# bash test.sh 
      Pleas input a user name:alongdidi
      User alongdidi doesn't exists.

      多分支if語句

      if TEST1; then
          CMD1
      elif TEST2; then
          CMD2
      elif TEST3; then
          CMD3
      ...
      else
          CMD-LAST
      fi

      當(dāng)TEST1為真時執(zhí)行CMD1,否則判斷TEST2;當(dāng)TEST2為真時執(zhí)行CMD2,否則判斷TEST3;以此類推,都不符合條件的話則執(zhí)行CMD-LAST。

      判斷文件類型的示例。

      #!/bin/bash
      read -p "Please input only a absolute file path:" file
      
      if [ -z $file ]; then
          echo "You must input something."
          exit 2
      fi
      
      if [ ! -e $file ]; then
          echo "No such file $file"
      elif [ -d $file ]; then
          echo "File $file is a directory."
      elif [ -L $file ]; then
          echo "File $file is a symbolic."
      elif [ -b $file ]; then
          echo "File $file is a block special file."
      elif [ -c $file ]; then
          echo "File $file is a character special file."
      elif [ -S $file ]; then
          echo "File $file is a socket file."
      elif [ -f $file ]; then
          echo "File $file is a regular file."
      else
          echo "File is unrecognized."
      fi

      執(zhí)行示例。

      [root@c7-server ~]# bash test.sh 
      Please input only a absolute file path:
      You must input something.
      [root@c7-server ~]# bash test.sh 
      Please input only a absolute file path:passwd
      No such file passwd
      [root@c7-server ~]# bash test.sh 
      Please input only a absolute file path:/etc/passwd        
      File /etc/passwd is a regular file
      [root@c7-server ~]# bash test.sh 
      Please input only a absolute file path:/root/
      File /root/ is a directory.
      [root@c7-server ~]# bash test.sh 
      Please input only a absolute file path:/etc/rc.local
      File /etc/rc.local is a symbolic.

      字符鏈接文件也可以被認(rèn)為是普通文件(regular),因此建議將普通文件的判定放置在較靠后的位置。

      注意:if語句是可以嵌套的。

      [root@c7-server ~]# cat test.sh
      #!/bin/bash
      if [ -e /dev/sda ]; then
          if [ -b /dev/sda ]; then
              echo "It's a block file."
          fi
      fi
      [root@c7-server ~]# bash test.sh
      It's a block file.

      其他示例

      編寫一個腳本,僅可接收一個參數(shù),此參數(shù)應(yīng)是一個用戶名稱。判斷該用戶名是否存在,若存在則輸出用戶的信息,否則就創(chuàng)建該用戶并設(shè)置默認(rèn)密碼(password)。

      #!/bin/bash
      
      if [ $# -ne 1 ];then
          echo "You must input just one argument!"
          exit 2
      fi
      
      if id $1 &> /dev/null; then
          id $1
      else
          useradd $1
          echo "password" | passwd --stdin $1 &> /dev/null
      fi

      編寫一個腳本,接收兩個數(shù)值類參數(shù),并輸出其中較大的那個。

      #!/bin/bash
      
      if [ $# -ne 2 ]; then
          echo "Please input exact two number arguments."
          exit 1
      fi
      
      if [ $1 -eq $2 ]; then
          echo "Number $1 and $2 are equal."
      elif [ $1 -gt $2 ]; then
          echo "The greater is $1."
      else
          echo "The greater is $2."
      fi

      編寫一個腳本,接收一個用戶名作為參數(shù),并判斷其奇偶性。

      [root@c7-server ~]# cat even_odd_if.sh 
      #!/bin/bash
      
      if [ $# -ne 1 ]; then
          echo "You must input just one argument."
          exit 1
      fi
      
      var=$[$(id -u $1)%2]
      if [ $var -eq 0 ]; then
          echo "The UID of $1 is even."
      else
          echo "The UID of $1 is odd."
      fi

      編寫一個腳本,接收兩個文件名作為參數(shù),返回文件的行數(shù)以及判斷哪個文件的行數(shù)比較多。

      #!/bin/bash
      
      if [ $# -ne 2 ]; then
          echo "You must input exat 2 arguments."
          exit 1
      fi
      
      if [ ! -e $1 -o ! -e $2 ]; then
          echo "File $1 or/and $2 doesn't/don't exist[s]."
          exit 2
      fi
      
      line1=$(wc -l $1 | cut -d " " -f 1)
      line2=$(wc -l $2 | cut -d " " -f 1)
      echo "The lines of $1 is $line1"
      echo "The lines of $2 is $line2"
      
      if [ $line1 -gt $line2 ]; then
          echo "$1 has more lines."
      elif [ $line1 -lt $line2 ]; then
          echo "$2 has more lines."
      else
          echo "They have same lines."
      fi

      編寫一個腳本,傳遞一個用戶名作為參數(shù)給腳本,判斷用戶的類型。

      UID=0:管理員

      UID=1~999:系統(tǒng)用戶

      UID=1000+:普通用戶

      #!/bin/bash
      
      if [ $# -ne 1 ]; then
          echo "You must input exact one argument."
          exit 1
      fi
      
      if ! id $1 &> /dev/null; then
          echo "You must input an existed username."
          exit 2
      fi
      
      userId=$(id -u $1)
      if [ $userId -eq 0 ]; then
          echo "$1 is a admin user."
      elif [ $userId -lt 1000 ]; then
          echo "$1 is a system user."
      else
          echo "$1 is a normal user."
      fi

      編寫一個腳本,展示一個菜單供用戶選擇,菜單告知用戶腳本可以顯示的系統(tǒng)信息。

      #!/bin/bash
      
      cat << EOF
      disk) Show disk infomation.
      mem) Show memory infomation.
      cpu) Show cpu infomation.
      *) QUIT!
      EOF
      
      read -p "Your option is: " option
      if [ -z $option ]; then
          echo "You input nothing,QUIT!"
          exit 1
      elif [ $option == disk ]; then
          fdisk -l
      elif [ $option == mem ]; then
          free -m
      elif [ $option == cpu ]; then
          lscpu
      else
          echo "You input a illegal string,QUIT now!"
      fi

      在后面學(xué)習(xí)了循環(huán)之后,可以加上循環(huán),使得用戶在輸入錯誤的情況下,反復(fù)讓用戶輸入直到輸入正確的選項(xiàng)。

      #!/bin/bash
      
      cat << EOF
      disk) Show disk infomation.
      mem) Show memory infomation.
      cpu) Show cpu infomation.
      *) Again!
      EOF
      
      read -p "Your option is: " option
      
      while [ "$option" != disk -a "$option" != mem -a "$option" != cpu -o "$option" == "" ]; do
          echo "You input a illegal string. Usage {disk|mem|cpu}, case sensitive."
          read -p "Your option is: " option
      done
      
      if [ $option == disk ]; then
          fdisk -l
      elif [ $option == mem ]; then
          free -m
      elif [ $option == cpu ]; then
          lscpu
      fi

      這個腳本的難點(diǎn)我覺得在于while循環(huán)中的判斷應(yīng)該怎么寫,$option是否應(yīng)該加引號、字符串匹配右邊的字符(如disk)是否需要加引號、使用單中括號還是雙中括號、使用單引號還是雙引號。我也是一遍遍試直到瞎貓碰到死耗子才寫出來符合自己需求的bash代碼。

      具體涉及的難點(diǎn)包括但《Bash腳本編程學(xué)習(xí)筆記04:測試命令test、狀態(tài)返回值、位置參數(shù)和特殊變量》文章開頭說的那些,因此這里無法為大家做到準(zhǔn)確的分析。

       

      case語句

      像上述腳本中,我們反復(fù)對一個變量做字符串等值比較并使用了多分支的if語句。此類情況我們完全可以使用case語句來代替,使其更容易看懂。

      其官方語法如下:

      case word in
          [ [(] pattern [| pattern]…) command-list ;;]…
      esac

      case會將word和pattern進(jìn)行匹配,一旦匹配到就執(zhí)行對應(yīng)的command-list,并且退出。

      pattern基于bash的模式匹配,即glob風(fēng)格。

      pattern至少一個,可以有多個使用“|”分隔。

      pattern+command-list成為一個子句(clause),如下。

      [(] pattern [| pattern]…) command-list ;;

      每個子句,都會以“;;”或者“;&”或者“;;&”結(jié)束。基本上只會使用“;;”。

      ;;:決定了一旦word第一次匹配到了pattern,就執(zhí)行對應(yīng)的command-list,并且退出。
      ;&和;;&:而這兩個是不會在第一次匹配到就立刻退出的,還會有其他后續(xù)的動作,幾乎很少用到,有需要的可以去看手冊。

      word在匹配前會經(jīng)歷:波浪符展開、參數(shù)展開、命令替換、算術(shù)展開和引號去除。

      pattern會經(jīng)歷:波浪符展開、參數(shù)展開、命令替換和算術(shù)展開。

      當(dāng)word的值是一個通配符的時候,表示默認(rèn)的case。類似多分支if語句最后的else。

      來個官方示例,簡單易懂。

      #!/bin/bash
      
      echo -n "Enter the name of an animal: "
      read ANIMAL
      echo -n "The $ANIMAL has "
      case $ANIMAL in
        horse | dog | cat) echo -n "four";;
        man | kangaroo ) echo -n "two";;
        *) echo -n "an unknown number of";;
      esac
      echo " legs."

      學(xué)會了case語句后,我們就可以對上面的多分支if語句的最后一個示例(顯示系統(tǒng)信息的)進(jìn)行改寫,改為case語句的。應(yīng)該不難,這里不演示了,我們嘗試新的腳本。

      我們嘗試寫一個bash服務(wù)類腳本,常見于CentOS 6系列的系統(tǒng)中的/etc/rc.d/init.d/目錄下。

      • 腳本的名稱一般就是服務(wù)名稱,不會帶“.sh”。
      • 服務(wù)腳本一般會創(chuàng)建一個空文件作為鎖文件,若此文件存在則表示服務(wù)處于運(yùn)行狀態(tài);反之,則服務(wù)處于停止?fàn)顟B(tài)。
      • 腳本只能接收四種參數(shù):start, stop, restart, status。
      • 我們并不會真正啟動某進(jìn)程,只要echo即可。啟動時需創(chuàng)建鎖文件,停止時需刪除鎖文件。
      • 適當(dāng)加入條件判斷使得腳本更健壯。
      #!/bin/bash
      #
      # chkconfig: - 50 50
      # Description: test service script
      #
      
      prog=$(basename $0)
      lockfile="/var/lock/subsys/$prog"
      
      case $1 in
          start)
              if [ -e $lockfile ]; then
                  echo "The service $prog has already started."
              else
                  touch $lockfile
                  echo "The service $prog starts finished."
              fi
          ;;
          stop)
              if [ ! -e $lockfile ]; then
                  echo "The service $prog has already stopped."
              else
                  rm -f $lockfile
                  echo "The service $prog stops finished."
              fi
          ;;
          restart)
              if [ -e $lockfile ]; then
                  rm -f $lockfile
                  touch $lockfile
                  echo "The service $prog restart finished."
              else
                  touch $lockfile
                  echo "The service $prog starts finished."
              fi
          ;;
          status)
              if [ -e $lockfile ]; then
                  echo "The service $prog is running."
              else
                  echo "The service $prog is not running."
              fi
          ;;
          *)
              echo "Usage: $prog {start|stop|restart|status}"
              exit 1
          ;;
      esac

      腳本編寫完成后,要放入服務(wù)腳本所在的目錄、給予權(quán)限、加入服務(wù)管控(chkconfig),最后就可以使用service命令進(jìn)行測試了。

      ~]# cp -av case_service.sh /etc/rc.d/init.d/case_service
      'case_service.sh’ -> '/etc/rc.d/init.d/case_service’
      ~]# chmod a+x /etc/rc.d/init.d/case_service
      ~]# chkconfig --add case_service
      ~]# chkconfig case_service on

      像這個服務(wù)類的腳本,我們在重啟時,可能執(zhí)行先停止后啟動,也可能執(zhí)行啟動。這些在啟動和停止時都有已經(jīng)寫好的代碼了。如果可以將代碼進(jìn)行重用的話,就可以減少很多代碼勞動。這就是之后要介紹的函數(shù)。

        本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多