亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Linux Shell系列教程之Shell判斷 if else 用法

原創(chuàng) 2016-11-12 10:20:32 366
摘要:if 語句通過關(guān)系運(yùn)算符判斷表達(dá)式的真假來決定執(zhí)行哪個(gè)分支。Shell 有三種 if else格式:if … fi 格式if … else … fi 格式if … elif … else … fi 格式下面我就分別就這幾種格式來為大家詳細(xì)介紹下。一、Shell判斷語法之if … else 格式if … else 格式的語法:if [ expression ] then

if 語句通過關(guān)系運(yùn)算符判斷表達(dá)式的真假來決定執(zhí)行哪個(gè)分支。

Shell 有三種 if else格式:

  • if … fi 格式

  • if … else … fi 格式

  • if … elif … else … fi 格式

下面我就分別就這幾種格式來為大家詳細(xì)介紹下。

一、Shell判斷語法之if … else 格式

if … else 格式的語法:

if [ expression ]
then
   Statement(s) to be executed if expression is true
fi

說明:

如果 expression 返回 true,then 后邊的語句將會(huì)被執(zhí)行;

如果返回 false,不會(huì)執(zhí)行任何語句。

最后必須以 fi 來結(jié)尾閉合 if,fi 就是 if 倒過來拼寫,后面也會(huì)遇見。

注意:expression 和方括號(hào)([ ])之間必須有空格,否則會(huì)有語法錯(cuò)誤。

使用舉例:

#!/bin/sh
a=400b=800if [ $a == $b ]
then
   echo "a is equal to b"
fi
if [ $a != $b ]
then
   echo "a is not equal to b"
fi

運(yùn)行結(jié)果:

a is not equal to b

二、Shell判斷語法之 if … else … fi 格式

if … else … fi 語句的語法

if [ expression ]
then
   Statement(s) to be executed if expression is true
else
   Statement(s) to be executed if expression is not true
fi

說明:

如果 expression 返回 true,那么 then 后邊的語句將會(huì)被執(zhí)行;

否則的話,將會(huì)執(zhí)行 else 后邊的語句。

使用舉例:

#!/bin/sh
a=400b=800if [ $a == $b ]
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi

執(zhí)行結(jié)果:

a is not equal to b

三、Shell判斷語法之if … elif … fi格式

if … elif … fi 語句可以對(duì)多個(gè)條件進(jìn)行判斷

語法:

if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

說明:

哪一個(gè) expression 的值為 true,就執(zhí)行哪個(gè) expression 后面的語句;

如果都為 false,那么不執(zhí)行任何語句。

使用舉例:

#!/bin/sh
a=400b=800
if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi

運(yùn)行結(jié)果:

a is less than b

四、其他說明

if … else 語句也可以寫成一行,以命令的方式來運(yùn)行,像這樣:

if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;

if … else 語句也經(jīng)常與 test 命令結(jié)合使用,如下所示:

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

輸出:

The two numbers are equal!

test 命令用于檢查某個(gè)條件是否成立,與方括號(hào)([ ])類似。


發(fā)布手記

熱門詞條