1. 程式人生 > >shell程式設計條件判斷

shell程式設計條件判斷

bash中的條件判斷

條件測試型別

    1、整數測試

    2、字元測試

    3、檔案測試

條件測試表達式

    [ expression(表示式) ] 中括號和表示式之間必須有空格

    -eq 測試是否相等,相等為真,不相等為假

    image.png

    -ne 不相等為真,相等為假

    -gt 大於為真

    -lt 小於為真

    -ge 大於等於為真

    -le 小於等於為真

命令間的邏輯關係

    && 與,第一個條件為真,則要驗證第二個條件是否為真;第一個條件為假,不驗證第二個條件,就為假

    || 或

    ! 非

變數的命名規則

    1、只能包含數字,字母,下劃線,不能以數字開頭

    2、不應該與系統已有的環境變數重名

    3、名字儘量有意義


指令碼練習(用邏輯關係)

1、如果使用者存在,則輸出user exists

    id user1 &> /dev/null  && echo "user1 exists"

2、如果使用者不存在,就新增使用者

    ! id user1 &> /dev/null  && adduser user1 

3、如果使用者已存在,就顯示使用者已存在,否則就新增使用者

    id user7 &> /dev/null && echo "user7 exists" || adduser user7

    image.png

4、如果使用者不存在,就新增使用者,否則就顯示使用者已存在

    ! id user1 &> /dev/null  && adduser user1 || echo "user1 exists"

5、如果使用者不存在,新增使用者並且給密碼,否則就顯示使用者已存在

    ! id user8 &> /dev/null && adduser user8 && echo "user8" | passwd --stdin user8 &> /dev/null ||echo "user8 exists"

    image.png

6、給定一個使用者,如果UID為零,就顯示管理員,否則顯示普通使用者

#!/bin/sh

username=user1

userid=`id -u $username`

[ $userid -eq 0 ] && echo "administrator" || echo "common user"

image.png


條件判斷,if語句控制結構


if 判斷條件; then

    表示式1

    表示式2

    表示式3

    ……

fi

if 判斷條件

then

    表示式1

    表示式2

    表示式3

    ……

fi


if 判斷條件; then

    表示式1

    表示式2

    表示式3

    ……

else 

    表示式1

    表示式2

    表示式3

    ……

fi

注意事項: fi單獨一行;then可以單獨一行; then在判斷條件後,用分號隔開


使用if條件判斷語句來實現 

1、如果使用者不存在,新增使用者並且給密碼,否則就顯示使用者已存在

if ! id user9 &> /dev/null ; then
            adduser user9
            echo "user9" | passwd --stdin user9 &> /dev/null
else
            echo "user9 exists"
fi

image.png


2、給定一個使用者,如果UID為零,就顯示管理員,否則顯示普通使用者

username=root
if [ `id -u $username` -eq 0 ] ; then
        echo "administrator"
else
        echo "common user"
fi

image.png