Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux綜合 >> 學習 Linux

shell 腳本條件控制與循環:if、case、for、while、until

if 條件語句

語法:

if [ 條件表達式 ]
then
    代碼
else
    代碼
fi

注意:if 與 [ 之間要有空格,條件表達式與兩側的 [ ] 也都要留空格,不能緊挨著;整個語句以 fi 結束。

shell 腳本條件控制與循環:if、case、for、while、until

第一次運行報錯:

shell 腳本條件控制與循環:if、case、for、while、until

原因是解釋器聲明寫錯了,#! 之後還要有一個 /,補上之後解釋器錯誤消失:

shell 腳本條件控制與循環:if、case、for、while、until

但仍有「沒有那個文件或目錄」的提示。把 echo 後的表達式注釋掉、改成輸出 small 與 bigger 後程序正常:

shell 腳本條件控制與循環:if、case、for、while、until

可見問題出在 echo 後的表達式,給它加上雙引號後運行成功:

shell 腳本條件控制與循環:if、case、for、while、until shell 腳本條件控制與循環:if、case、for、while、until

case 條件判斷

case 變量 in
str1)
命令串;;
str2)
命令串;;
*)
shell 腳本條件控制與循環:if、case、for、while、until shell 腳本條件控制與循環:if、case、for、while、until

出錯是因為沒有正確結尾——case 語句在 shell 中必須以 esac 收尾。接著又報錯:

shell 腳本條件控制與循環:if、case、for、while、until

原因是 * 後面的括號用了中文全形符號,改成英文半形,並把結束標識從 easc 糾正為 esac,結果就正常了。

for 循環

第一種形式:

for var in list
do
    命令串
done

list 可以是空格分隔的 $1 $2 $3,也可以是 1 2 3 這樣的字面值。

第二種形式省略 list:

for var
do
    命令串
done

此時 list 即命令行參數,每次循環 var 取一個參數。例:輸出命令行參數之和。

shell 腳本條件控制與循環:if、case、for、while、until

注意:echo 的 -e 參數是為了讓 \c 與 \b 生效,\c 表示輸出加數後不換行,\b 是退格,用來刪掉多餘的加號。

shell 腳本條件控制與循環:if、case、for、while、until

報錯原因:expr 不能與 test 的 -gt 混用,二者只能取其一,若改用 -gt 之外的寫法要注意 >= 前需加反斜線轉義。

shell 腳本條件控制與循環:if、case、for、while、until

仍然報錯:

shell 腳本條件控制與循環:if、case、for、while、until

原因是求和時等號兩端不能留空格,改掉之後:

shell 腳本條件控制與循環:if、case、for、while、until shell 腳本條件控制與循環:if、case、for、while、until

while 循環

while 條件表達式
do
    命令行串;
done

例:輸出命令行的每個參數。

shell 腳本條件控制與循環:if、case、for、while、until

shift 命令把命令行參數左移,讓原本第二位的參數變成第一位再輸出:

shell 腳本條件控制與循環:if、case、for、while、until

注意:while 的條件表達式同樣要用空格與 [ ] 分隔。若循環體中另用變量 n,寫成 -n 的一元表達式形式:

shell 腳本條件控制與循環:if、case、for、while、until

不加 -n 也能得到相同結果:

shell 腳本條件控制與循環:if、case、for、while、until

until 循環

until 條件表達式
do
    命令串;
done

until 與 while 邏輯相反:條件成立時退出循環,條件不成立才繼續執行。

Copyright © Linux教程網 All Rights Reserved