bash中如何實作條件判斷
條件判斷類型:
整數判斷(雙目判斷):
-eq:等于 、equal,測試兩個整數之間是否相等,比如$A -eq $B
-gt:大于、greater than
-lt:小于、lesser than
-ne:不等于、no equal
這裡也可以用另外一種寫法,比如[ 2 -ne 3 ]可以寫作[ ! 2 -eq 3 ]
-le:小于或等于、lesser or equal
-ge:大于等于、greater or equal
...
字元判斷:
檔案判斷:單目判斷
-e:exist判斷檔案是否存在
-d:directory判斷檔案是否為目錄
-r:read 判斷檔案是否可讀
-w:write ...........可寫
-x:Executable...........可執行
條件判斷的表達式:
[ expression ]
注意[] 最左和左右需要空格,這裡linux把表達式當成指令來判斷
` expression `
同樣需要注意空格,這裡linux把表達式當成關鍵字來判斷,至于兩者差別,暫時存疑
test expression
指令間的邏輯關系:
邏輯與:&&
使用邏輯與的時候,當第一個條件判斷為假,則後面條件不再判斷
邏輯或:||
使用邏輯或的時候,當第一個條件判斷為真,則後面條件不再判斷
邏輯非:!
對條件判斷結果進行取反
示例:
如果使用者user1不存在,則添加user1
[root@logstach ~]# id user1
id: user1: No such user
[root@logstach ~]# ! id user1 &> /dev/null && useradd user1 &> /dev/null
[root@logstach ~]# id user1
uid=3001(user1) gid=3001(user1) groups=3001(user1)
或者
id user1|| useradd user1
如果/etc/inittab檔案的行數大于100,就顯示'large file'
[ `wc -l /etc/inittab |cut -d' ' -f1 ` -gt 100 ] && echo "large file"
變量的指令規則:
隻能用數字、字母和下劃線組成
不能用數字開頭
不應該與系統環境變量重名
最好做到見名知義
練習:
如果使用者存在,就顯示已經存在,否則添加此使用者
id user1 && echo 'user exists!' || useradd user1
如果使用者不存在就添加,否則顯示已經存在
!id user1&&useradd user1 ||echo 'user1 already exists!'
如果使用者不存在,添加并給其與使用者名同名的密碼,否則顯示其已經存在。
id user1 && echo 'user already exists!'|| useradd user1 && echo ‘user1'|passwd user1 --stdin
[root@logstach ~]# id user1 && echo 'user ?already exists!' || useradd user1 && echo 'user1'|passwd user1 --stdin
user ?already exists!
Changing password for user user1.
passwd: all authentication tokens updated successfully.
[root@logstach ~]# id user1 && ?echo 'user ?already exists!' ||( useradd user1 && echo 'user1'|passwd user1 --stdin)
[root@logstach ~]#
注意:這裡如果不加()的話,當shell執行到||時不執行useradd user1,但是它會繼續往下讀,到第二個&&時,把前面 id user1 && echo 'user ?already exists!' || useradd user1當成一個整體,發現整體結果為真,則繼續執行後面的内容passwd user1 --stdin。加()可以告訴shell,
useradd user1 && echo 'user1'|passwd user1 --stdin是一個整體。
練習:寫一個腳本,完成以下要求:
添加3個使用者user1、user2、user3,但要先判斷使用者是否存在,不存在而後再添加
添加完成後,顯示最後添加了哪幾個使用者,當然,不能包含已經存在而沒有添加的
最後顯示系統上有幾個使用者。
#!/bin/bash
! id user1 &> /dev/null && useradd user1 && echo 'useradd user1'
! id user2 &> /dev/null && useradd user2 && echo 'useradd user2'
! id user3 &> /dev/null && useradd user3 && echo 'useradd user3'
TOTAL=`cat /etc/passwd|wc -l`
echo "$TOTAL users."
給定一個使用者:
如果uid為0就顯示為管理者
否則,就顯示其為普通使用者
USER=user1
USERID=`grep $USER /etc/passwd|cut -d: -f3`
[ $USERID -eq 0 ] && echo "administrator!" || echo "common user."
條件判斷,控制結構:
單分支if語句:
if 判斷條件;then
statement1
statement2
..
fi
then如果另起一行,則;可以省略,否則不行
雙分支if語句:
if 判斷條件;then
...
else
statement2
多分支if語句:
if 判斷條件1;then
elif 判斷條件2;then
statement2
elif 判斷條件3;then
statement3
....
statement4
if ls /var ...和if `ls /var` ...的差別:
if ls /var 會根據指令的執行狀态結果進行判斷,0為真,1-255為假,而if `ls /var`則會報錯,因為 `ls /var`傳回的是指令的執行結果,if 不能對其進行判斷,但是如果添加條件使其能滿足條件判斷的條件,則可以進行判斷,例如:
if [ `ls /var|wc -l` -gt 20 ];then
echo 'large directory'
fi
本文轉自biao007h51CTO部落格,原文連結: http://blog.51cto.com/linzb/1731741,如需轉載請自行聯系原作者