shell腳本編程:條件判斷if語句使用小結

shell腳本編程,有三種控制結構分別是:順序結構,條件判斷結構,循環結構。本文將總結shell腳本中條件判斷結構的使用方法。

條件判斷結構分爲三種,單分支,雙分支,多分支,等結構。

單分支結構的語法如下:

if [ expression  ] ;then

    statement1

    statement2

    .........

fi


雙分支語法結構:

if [ expression ];then

    statement1

    statement2

    .....

else

    statement3

    statement4

    ......

fi


多分支語法結構:

if [ expresion1 ];then

    statement1

    ....

elif [ expression2 ];then

    statement2

    ......

elif [ expression3 ];then

    statement3

    ......

else

    statement4

    ......

fi

需要注意在什麼時候需要使用then,以及then前面的分號是必不可少的,否則會出錯。

if 永遠和fi配對

if 或者elif 後面一定有then


多分支條件語句實例:

[root@bogon sh]# cat test.sh
#!/bin/bash
read -p 'please input your file ' FILE
#FILE=/etc/passwddd
if [ ! -e $FILE ];then
    echo "$FILE is not exist "
    exit 3
fi
if [ -f $FILE ];then
    echo "$FILE is common file"
elif [ -d $FILE ];then
    echo "$FILE is directory file"
elif [ -x $FILE ];then
    echo "$FILE can be excuteable"
elif [ -w $FILE ];then
    echo "$FILE can be written"
elif [ -r $FILE ];then
    echo "$FILE can read"
else
    echo "unkown file"
fi


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章