Linux指令碼程式設計之if判斷語句

2021-07-25 18:43:53 字數 3014 閱讀 1350

linux指令碼程式設計中最基本的結構化語句為 if-then語句,if-then語句的格式如下:

if command

then

commands

fi

執行過程為:首先執行在if行定義的命令,如果命令的退出碼是0(成功執行命令)

,則將執行 then後面的命令,如果退出碼不為0,then後的命令將不會執行,

例如:

$ cat test01                 

#!/bin/bash

#測試乙個正常的命令

if date

then

echo "date worked"

fi$ ./test01

2023年 01月 03日 星期二 08:31:30 cst

date worked

下面是乙個反面例子:

$ cat test02

#!/bin/bash

#測試乙個不存在的命令

if asasaas

then

echo "the command doesn't work "

fiecho "this is outside if statement"

$ ./test02

./test.sh:行3: asasaas: 未找到命令

this is outside if statement

注意:命令出錯時的錯誤資訊也會顯示在螢幕上,可以使用重定向將其定位到其它地方。

用慣其它程式語言的同學會覺得 shell程式設計的if語句有點彆扭,可以使用下面這種寫法來**一下強迫症:

if command;then

commands

fi

分支判斷語句還有下面兩種形式:

if command

then

commands

else

commands1

fi***************====此為分隔線*************************==

if command1

then

commands1

elif command2

then

commands2

elif command3

then

commands3

else

commands4

fi

上面介紹的if語句判斷的都是shell命令的退出碼,很多時候我們需要判斷其它

條件,如數字比較,字串比較等,在bash shell中可以使用test命令判斷其它條件。

test 命令有兩種寫法:

1.第一種寫法

if test condition

then

commands

fi***************此為分隔線******************************==

2.第二種寫法

if [ condition ]

then

commands

fi

使用第二種寫法時一定要注意:前半個括號後面和後半個括號前面必須加個空格,否則會報錯。

test命令可以判斷以下3種條件:

a.數值比較

n1 -eq n2  檢查n1是否相等n2                 n1 -le n2    檢查n1是否小於或相等n2

n1 -ge n2  檢查n1是否大於或等於n2     n1 -lt n2     檢查n1是否小於n2

n1 -gt n2  檢查n1是否大於n2                  n1 -ne n2   檢查n1是否不相等n2

b.字串比較

str1 = str2    檢查str1與str2是否相同           str1 > str2  檢查str1是否大於str2

str1! = str2   檢查str1與str2是否不同           -n str1        檢查str1長度是否大於0

str1 < str2    檢查str1是否小於str2               -z str1        檢查str1長度是否為0

需要注意的一點是:這裡的 '>'和'<'需要轉義 前面加個'\',例如

$ cat test03

#!/bin/bash

val1=hello

val2=hi

if [ $val1 \> $val2 ]

then

echo "$val1 > $val2"

else

echo "$val1 < $val2"

fi$ ./test04

hello < hi

c.檔案比較

-d   file                 檢查file是否存在並且是乙個目錄

-e   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舊

plsql程式設計之,迴圈語句和判斷語句

作業 輸出 薪水等級 2 5 等級 最低和 最高薪水 set serveroutput on declare mysal number 1 myhi number mylo number begin loop if mysal 5 then exit end if select losal,hisa...

shell指令碼程式設計之條件判斷

1 shell指令碼學習 2 比較兩個數字大小 2 linux 中清空或刪除大檔案內容的五種方法 3 shell 清空檔案內容 整數測試 字元測試 檔案測試1 expression 命令測試 2 expression 關鍵字測試 3 test expression eq 測試兩個整數是否相等 相等為...

shell指令碼的條件判斷語句

條件判斷,顧名思義,就是對當前引數進行相關條件的比較,如果符合要求就進行相對應的操作,條件語句涉及到兩種語法,if和case,兩種語法都各具特色,我們可以通過例項來進行比較 if 判斷條件1 then 條件為真的分支 elif 判斷條件2 then 條件為真的分支 elif 判斷條件3 then 條...