天天看點

SHELL控制流結構筆記

                            SHELL控制流結構

  man  test 可以看見這些  

  比較符号:-lt小于 -le小于等于   -gt大于   -ge大于等于  -ne不等于   -eq等于 

            < 小于(需要雙括号),如:(("$a" < "$b"))

            <= 小于等于(需要雙括号),如:(("$a" <= "$b"))

            > 大于(需要雙括号),如:(("$a" > "$b"))

            >= 大于等于(需要雙括号),如:(("$a" >= "$b"))  

=或==(需要雙括号),如:if [ "$a" == "$b" ]

           -b file            若檔案存在且是一個塊特殊檔案,則為真

           -c file            若檔案存在且是一個字元特殊檔案,則為真

           -d file            若檔案存在且是一個目錄,則為真

           -e file            若檔案存在,則為真

           -f file            若檔案存在且是一個規則檔案,則為真

           -g file            若檔案存在且設定了SGID位的值,則為真

           -h file            若檔案存在且為一個符合連結,則為真

           -k file            若檔案存在且設定了"sticky"位的值

           -p file            若檔案存在且為一已命名管道,則為真

           -r file            若檔案存在且可讀,則為真

           -s file            若檔案存在且其大小大于零,則為真

           -u file            若檔案存在且設定了SUID位,則為真

           -x file            若檔案存在且可執行,則為真

           -o file            若檔案存在且被有效使用者ID所擁有,則為真

   -z string          若string長度為0,則為真

           -n string          若string長度不為0,則為真

           string1 = string2  若兩個字元串相等,則為真

           string1 != string2 若兩個字元串不相等,則為真

if  then else語句:

 if 條件 1

    then 指令1

 elif  條件 2

     then  指令2

 else   

      指令3

 fi 完成

   如果if和then在同一行那指令格式為 if 條件1;then

 eg:

#####vim name.sh

#!/bin/bash

#name.sh

echo -n "Enter you name:"

read NAME

if [ "$NAME" == " " ]; then

   echo "you did not enter you name"

else

   echo "you name is: $NAME"

fi

####儲存退出,chmod +x name.sh

#### 運作 ./name.sh

[root@localhost ~]# ./name.sh 

Enter you name:tony (這個名字你是輸入的)

you name is: tony

eg:copy一個檔案,如果檔案不存在會提示系統錯誤的資訊,和提示自己給的資訊

####vim ifcp.sh

#ifcp.sh

if cp test1.txt myfile.txt; then

   echo "copy is successful"

   echo "`basename $0`:no such test1.txt file" >&2

####儲存退出,chmod +x ifcp.sh

####運作 ./ifcp.sh  -n (-n參數可以檢查腳本是否有文法錯誤)

[root@localhost ~]# ./ifcp.sh 

cp: cannot stat `test1.txt': No such file or directory

ifcp.sh:no such test1.txt file

eg:copy一個檔案,檔案不存在系統提示的資訊不顯示在螢幕上,顯示提示自己給的資訊

if cp test1.txt myfile.txt 2>/dev/null; then

####運作 ./ifcp.sh

eg:copy一個檔案,檔案存在則提示copy is successful

if cp 1.txt myfile.txt 2>/dev/null; then

   echo "`basename $0`:no such test1.txt file" 

copy is successful

[root@localhost ~]# cat myfile.txt 

the end

解釋:`bsename $0`值顯示目前腳本或指令的名字,$0顯示會包括目前腳本或指令的路徑

       >&2重定向到标準錯誤,輸出到螢幕上

eg:一個if---elif---elif--else的語句, -z的參數不知道是什麼意思,自己可以man test檢視一下,注意空格和分号,引号

#####vim  ifelse.sh

#ifelse.sh

echo -n "Enter your name:"

if [ -z $NAME ] || [ "$NAME" = " " ];then

   echo "you did not enter a name"

elif [ "$NAME" = "root" ];then

   echo "Hello root"

elif [ "$NAME" = "tony" ];then

   echo "Hello tony"

   echo "hi,$NAME"

####儲存退出,chmod +x ifelse.sh

####運作 ./ifelse.sh

[root@localhost ~]# ./ifelse.sh 

Enter your name:root

Hello root

Enter your name:tony

Hello tony

Enter your name:jie

hi,jie

case語句:

   case值 in

   模式1)

      指令1

  ;;

   模式2)

      指令2

  esac

   case取值後面必須為單詞in,每一模式必須以右括号結束。取值可以為變量或常數,比對發現取值符合某一模式後,期間

 所有指令開始執行直至;;.模式比對符合*表示任意字元,?表示任意單字元,[..]表示類或範圍中任意字元

eg:

######vim case.sh

#case.sh

echo -n "Enter a number from 1 to 3:"

read ANS

case $ANS in

   1)

      echo "you select 1"

      ;;

   2)

     echo "you select 2"

     ;;

   3)

    echo "you select 3"

    ;;

   *)

    echo "`basename $0`:this is not between 1 and 3 ">&2

    exit

esac

#####儲存退出,chmod + case.sh

####運作 ./case.sh

[root@localhost ~]# ./case.sh 

Enter a number from 1 to 3:1

you select 1

Enter a number from 1 to 3:2

you select 2

Enter a number from 1 to 3:3

you select 3

Enter a number from 1 to 3:5

case.sh:this is not between 1 and 3 

for循環:

   for 變量名 in 清單

   do  

         指令1

 指令2

   done  

   當變量值在清單裡,for循環即執行一次所有指令,使用變量名通路清單中取值,指令可為任何有效的shell指令和語句,變量名

為任何單詞,in清單用法是可選的,如果不用它,for循環使用指令行的位置參數。in清單可以包含替換,字元串和檔案名。

eg:in後面的參數為一個清單

#####vim for1.sh

#for1.sh

for loop in 1 2 3 4 5

do

   echo $loop

done

####儲存退出,chmod +x for1.sh

####運作./for1.sh

[root@localhost ~]# ./for1.sh 

1

2

3

4

5

eg:in後面的參數為一個字元串

#####vim for2.sh

#for2.sh

for loop in "orange red bue grey"

  echo $loop“

####儲存退出,chmod +x for2.sh

####運作./for2.sh

[root@localhost ~]# ./for2.sh 

orange red bue grey

把for2.sh裡面的内容for loop in "orange red bue grey"  改成for loop in orange red bue greyz則in後面的分行顯示

eg:in後面的參數為一個指令,``反引号裡面的是系統的指令

#####vim for3.sh

#for3.sh

for jie in `cat myfile.txt`

    echo $jie

####儲存退出,chmod +x for3.sh   

[root@localhost ~]# ./for3.sh    

the

end

eg:一個for和if結合的列子

####vim for4.sh

#for4.sh

echo "zhe li mian end you yi ge end" >myfile.txt

for JIE in `cat myfile.txt`

    if [ "$JIE" = "end" ];then

       echo "it is:$JIE"

    else

       echo "it is not end,it is:$JIE"

    fi

#####儲存退出,chmod +x for4.sh

####運作./for4.sh

[root@localhost ~]# ./for4.sh 

it is not end,it is:zhe

it is not end,it is:li

it is not end,it is:mian

it is:end

it is not end,it is:you

it is not end,it is:yi

it is not end,it is:ge

until循環:

   until 條件

   do 

       指令1

   指令2

   ...

   done

條件可以為任意測試條件,測試發生在循環末尾,是以循環至少執行一次

eg:檢查磁盤空間的大小,每隔300s檢查磁盤空間,超過指定的數字就發郵件給root使用者

######vim until.sh

#until.sh

Part="/home"

LOOK_OUT=`df | grep "$Part" | awk '{print $5}'| sed 's/%//g'`

echo $LOOK_OUT

until [ " $LOOK_OUT" -gt "90" ]

   echo "this Filesystem is empty" |mail root

   LOOK_OUT=`df | grep "$Part" | awk '{print $5}'| sed 's/%//g'`

     sleep 300

done   

#####儲存退出,chmod +x until.sh

####運作./until.sh

while循環:

      while 指令

      do

   指令1

  done

 在while和都之間雖然通常指使用一個指令,但可以放幾個指令,指令通常用作測試條件 

######vim while.sh

#while.sh

NAME=name.txt

if [  -e "$NAME"  ];then

      echo -e "zhui jia \n jin qu \n yi juhua " >> $NAME

       touch $NAME

      echo -e "zhe ge wen jian \n shi xin \n jian de " > $NAME

while read LINE

     echo $LINE 

done < $NAME

######儲存退出,chmod +x while.sh

####運作 ./while.sh

if [  -e "$NAME"  ]    //判斷這個檔案有木有,若果有則會追加一句話,沒有則會建立一個檔案,然後會添加一句話

然後通過循環把他顯示輸出,如果沒有這個檔案,運作第一遍則隻會出現echo -e "zhe ge wen jian \n shi xin \n jian de " > $NAME

這個裡面的,如果運作第二遍,則 echo -e "zhe ge wen jian \n shi xin \n jian de " > $NAME會顯示一次,然後

echo -e "zhui jia \n jin qu \n yi juhua " >> $NAME會輸入一次,運作第三遍,則echo -e "zhui jia \n jin qu \n yi juhua " >> $NAME             

會顯示更多遍

break控制:

  退出循環,如果是在一個嵌入循環裡,可以指定n來跳出循環的個數,

######vim break.sh

#break.sh

while :

     echo -n "Enter any number [  1...5 ]:"

     read  ANS

   case  $ANS in

     1|2|3|4|5)

        echo "Your enter a number between 1 and 5."

        ;;

     *)

        echo "Wrong number,bye."

        break

    esac

######儲存退出,chmod +x break.sh

####運作 ./break.sh

[root@localhost ~]# ./break.sh 

Enter any number [  1...5 ]:1

Your enter a number between 1 and 5.

Enter any number [  1...5 ]:3

Enter any number [  1...5 ]:7

Wrong number,bye.

解釋:while : ,while後面接一個: 表示while語句永遠為真,用break跳出循環。

continue控制:

   跳過循環步

#####vim breakcontinue.sh 

        echo -n "Wrong number,continue(y/n?)."

        read IS_CONTINUE

        case $IS_CONTINUE in

             y|yes|Y|Yes)

                 continue;

                 ;;

              *) break

        esac

######儲存退出, chmod +x breakcontinue.sh 

#####運作, ./breakcontine.sh

[root@localhost ~]# ./breakcontinue.sh 

Wrong number,continue(y/n?).y

Enter any number [  1...5 ]:6

Wrong number,continue(y/n?).n   

vim check_server.sh

####

echo "this script will to find which service have started"

#to find www service

testing=`netstat -tlun | grep ":80"`

if [ -n "$testing" ];then                ##if no null is true

    echo "WWW server has started!"

#to find vsftpd service

testing=`netstat -tlun | grep ":21"`

if [ "$testing" != "" ];then            ###if no null is true

    echo "vsftpd server has started!"

#to find ssh service

testing=`netstat -tlun | grep ":22"`

if [ -n "$testing" ];then

    echo "SSH server has started!"

#to find mail service

testing=`netstat -tlun | grep ":25"`

if [ "$testing" != ""  ];then

    echo "MAIL server has started!"

#####

function功能

格式:

function fname()

{

  程式段

}

function的設定一定要在程式的最前面

擁有内建變量,$0表示函數名稱,後續接的變量标記為$1,$2,$3....

vim func.sh

###

function printinfo()

    echo "you choice is"

case $1 in

    "one")

printinfo;echo $1 | tr -s 'a-z' 'A-Z'

;;

    "two")

        printinfo;echo $1 | tr -s 'a-z' 'A-z'

esac  

shell腳本實作1+2+...+100

vim sum.sh

i=0

s=0

while [ "$i" -lt 100 ]

    i=$(($i+1))

    s=$(($s+$i))

echo "1+2+3+...+$i=$s"

####   

vim sum1.sh

for ((i=0;i<=100;i++))

echo "1+2+..+100=$s"

echo "i=$i"

for的另一種格式

vim for.sh

for animal in cat dog pig

        case $animal in

                "cat")

                        echo "$animal miao miao jiao"

                        ;;

                "dog")

                        echo "$animal wang wang jiao"

                "pig")

                        echo "$animal luo luo jiao"

                "*")

                        echo "$animal jiao mei jiao"

本文轉自 jie783213507 51CTO部落格,原文連結:http://blog.51cto.com/litaotao/1187977,如需轉載請自行聯系原作者