if 語句包括 字串測試,檔案測試,數字測試
基本的語法為
if test command
then
elsefi或
if [ command ]
then
else
fitest的用法等價於[ ]
例如:if test "hello" = "hello" 與 if [ "hello" = "hello" ] 等價
注意:[ 與 "hello" 與 = 與 "hello" 與 ] 之間存在 空格
1, 下面舉上乙個字串測試的小例子
#字串比較
#!/bin/bash
if [ "hello" = "hello" ]
then
echo "hello" == "hellohello"
else
echo "hello" != "hello"
fiif [ "hell0" = "hell0" ]
then
echo "hell0" == "hello"
else
echo "hell0" != "hello"
fi-z 代表字串為空
-n 代表字串大於0
# shell_if_file 檔案測試
#!/bin/bash
#判斷是否有可執行許可權
if [ -x ./file_test ]
then
echo "is -x"
else
echo "isn't -x"
fi#判斷是否為普通檔案
if [ -f ./file_test ]
then
echo "is general"
else
echo "isn't general"
fi其中:-x 是判斷是否有可執行許可權, -f 是判斷是否為普通檔案
3, 下面為數字測試的小例子, -eq代表相等, -ne代表不等, -lt 代表小於, -le 代表小於等於, -gt 代表大於, -ge 代表大於等於
# shell_if_number 數字比較
#!/bin/bash
echo "please input number1:"
read number1
echo "please input number2"
read number2
#判斷相等
if test "$number1" -eq "$number2"
then
echo "number1 == number2"
else
echo "number1 != number2"
fiecho "please input number1:"
read number1
echo "please input number2"
read number2
#判斷不等
if test "$number1" -ne "$number2"
then
echo "number1 != number2"
else
echo "number1 == number2"
fiecho "please input number1:"
read number1
echo "please input number2"
read number2
#小於if test "$number1" -lt "$number2"
then
echo "number1 < number2"
else
echo "number1 isn't < number2"
fiecho "please input number1:"
read number1
echo "please input number2"
read number2
#小於等於
if test "$number1" -le "$number2"
then
echo "number1 <= number2"
else
echo "number1 isn't <= number2"
fiecho "please input number1:"
read number1
echo "please input number2"
read number2
#大於if test "$number1" -gt "$number2"
then
echo "number1 > number2"
else
echo "number1 isn't > number2"
fiecho "please input number1:"
read number1
echo "please input number2"
read number2
#大於等於
if test "$number1" -ge "$number2"
then
echo "number1 >= number2"
else
echo "number1 isn't >= number2"
fi
shell程式設計 if語句
今天開始學習shell程式設計,通過看書,練習了幾個基本的小例子,下面總結一些知識點分享給大家 if 語句包括 字串測試,檔案測試,數字測試 基本的語法為 if test command then else fi或 if command then else fitest的用法等價於 例如 if te...
shell程式設計 if語句
if語句形式 if condition then statement s fiif condition then statement s fi請注意condition後面的分號 當if和then位於同一行時候,這個分號是必須的,否則會有語法錯誤。bin bash username student i...
shell程式設計 迴圈語句
while語句 while語句格式 while 表示式 do command command done while 和 if 的條件表示式完全相同,也是 或commad或test while 表示式 if 表示式 表示式值為0,則迴圈繼續 表示式值為0,then 表示式值為非0,則迴圈停止 表示式值...