標籤:linux linux shell 編程 shell 指令碼
前面有了變數的概念和邏輯運算子,就可以寫判斷語句了,不過這裡注意中括弧的兩邊必須得留空格,不然報錯.
運算子
- 賦值, 用 let 語句, 如 let "a=1"
- 算數運算, 支援 + - * / %(模運算) **(冪運算)
- 位元運算符, 支援 <<(左移) >>(右移) &(按位與) |(按位或) ~(按位取反) ^(按位異或)
if / then / else 語句
先舉個栗子唄~
#!/bin/bashread var1if [ "$var1" -gt 15 ]thenecho "$var1 is greater than 15"else echo "$var1 is less than 15"fi
注: 聽說如果 else 裡面又嵌套一個 if 語句,可以考慮用 elif 語句,這樣子可以減少 fi 的數量,使得結構清晰
case 語句
#!/bin/bashread dayweek=(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)case $day in1)echo ${week[1]};;2)echo ${week[2]};;3)echo ${week[3]};;4)echo ${week[4]};;5)echo ${week[5]};;6)echo ${week[6]};;7)echo ${week[0]};;*)echo "no such day...";;esac
for迴圈
下面寫了四種格式,貌似還有別的
#!/bin/bashfor var1 in Mon Tue Wed Thu Fri Sat Sundo echo "Today is $var1 "donefor var2 in {1..10..2}doecho "This is $var2"donefor var3 in $(seq 1 2 10) doecho "I have a/an $var3"donefor var4 in $(ls)doecho "Here is the file $var4"done
while迴圈
#!/bin/bashi=1while (( i <= 5 ))doecho "i = $i"let "++ i"done
select語句
這個select語句到時木有見過,啟動並執行時候可以和使用者互動, 運行一下下面的程式就懂了. 注意不加break的話,會死迴圈下去
#!/bin/bashecho "Which color do you like?"select var1 in red green bluedoecho "I like $var1"breakdone
Linux shell指令碼編程入門(二) 迴圈語句