Shell程式設計 流控制

2021-09-08 00:01:39 字數 1900 閱讀 4278

if語句

1 寫if語句時不要隨意加空格,比如if [ 1<2 ],這是假,而if [ 1 < 2 ]就是真了,因為1和《之間有空格。注意與1,2之間的空格是合法的,總結一下就是,shell中表示式中最好不要加空格,比如a=1, 1<2, 2=2等等,如果加上空格,往往會產生錯誤。

2 使用test,格式:if test expression

if test 1<2

then echo "no"

else echo "yes"

fi 輸出yes

使用,格式:if [ expression ] (注意:與表示式之間有乙個空格)

if [ 2<1 ]

then echo "no"

else echo "yes"

fi輸出no

3 使用可以進行三種比較,檔案測試,字串比較,數字比較

(1)檔案測試,判斷sh.exe是否存在

if [ -e sh.exe ] #判斷目錄是否存在用-d

then echo "sh.exe exists"

else echo "sh.exe does not exists"

fi(2)字串比較

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

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

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

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

if [ "abc"="abc" ]

then echo "yes"

else echo "no"

fi(3)數字比較

[int1 operator int2],這裡int1和int2都是整數,如果有乙個是字串,則按0對待,操作符可以是下面這些

-eq 等於

-ne 不等於

-lt 小於

-le 小於等於

-gt 大於

-ge 大於等於

數字比較常用來檢測乙個命令是否成功執行,在shell中成功執行的命令返回0,而非零整數則表示命令出錯,下面是乙個例子

if [ $? -ne 0 ] # $?儲存乙個命令,乙個指令碼或者乙個函式的退出狀態

then echo " an error was encountered"

exit

fi4 compound expressioin 復合表示式

!expr 將expr的bool值取反

expr1 -a expr2 相當於 [ expr1 ] && [ expr2 ]

expr1 -o expr2 相當於 [ expr1 ] || [ expr2 ]

而[expr1] && [expr2] 還有一種等價寫法 [[ expr1 && expr2 ]]

下面的兩個命令是等價的

if [ -z "$dthome" ] && [ -d /usr/dt ] ; then dthome=/usr/dt ; fi

if [ -z "$dthome" -a -d /usr/dt ] ; then dthome=/usr/dt ; fi

5 case語句

case word in

pattern1)

list1

;;pattern2)

list2

;;esac

或者case word in

pattern1) list1 ;;

pattern2) list2 ;;

esac

case語句的強大之處再於它可以使用模式,比如

case "$term" in

*term)

term=xterm ;;

network|dialup|unknown|vt[0-9][0-9][0-9])

term=vt100 ;;

esac

Shell指令碼程式設計 流控制(一)

在指令碼中有兩種強大的流控制機制可以使用 if語句 case語句 1 if語句 基本語法 if list1 then list2 elif list3 then list4 else list5 fi乙個例項 if uuencode koala.gif koala.gif koala.uu then...

shell指令碼 流控制

語法結構 如果 條件判斷中有多條命令,則根據最後一條命令的執行結果進行評估 ifcommand then command elif command then command else command fi bin bash x 5if x 5 then echo x equals 5 else ec...

shell的執行流控制

case 1 in word1 word1 action1 word2 word2 action2 action3 esac dnf install expect y 問題指令碼 bin bash read p what s your name name read p how old are you...