平常我們在命令列一次敲一條指令、看一次回應。若需要連續跑幾十條才拿到最後結果,這種做法顯然沒效率。要解決它,就用 shell 腳本。
Shell 程式很像 C 語言等程式語言,卻沒那麼複雜。本質上它就是一個檔案裡排著一串 Linux 指令與工具,執行時由 shell 逐條解釋。
建立一個名為 date 的檔案放在 ~/bin:
#Program date #usage: show the date in this way(註解) echo "Mr.$USER,Today is:" echo date "+%B%d%A" echo "Wish you a lucky day !"
存檔後它還不能跑,要給執行權限:
chmod +x date
之後就能像用 ls 一樣執行:
[beichen@localhost bin]$ date Mr.beichen,Today is: January 13 Friday Wish you a lucky day !
想在任何目錄都能執行,把 bin 加進 PATH:
[beichen@localhost bin]$ PATH=$PATH:$HOME/bin
另一種跑法是把檔案當參數丟給 shell:
[beichen@localhost /]$ bash date
也可以用「點加空格加檔名」的方式在目前 shell 中執行:
[beichen@localhost /]$ . date
這種做法不推薦,因為腳本會直接影響目前的 shell 環境。
位置參數由系統提供,用 $N 取值。Linux 會把命令字串分段編號,從 0 開始:0 是程式名,1 之後才是傳入的參數。
內部參數還有這幾個:$# 參數總數、$? 上一個程式的退出狀態(正常為 0)、$* 所有參數組成的字串。
寫一支 P1 來看:
echo "Program name is $0" echo "There are totally $# parameters passed to this program" echo "The last is $?" echo "The parameters are $*"
[beichen@localhost bin]$ P1 this is a test program Program name is /home/beichen/bin/P1 There are totally 5 parameters passed to this program The last is 0 The parameters are this is a test program
再來一支把檔案丟進回收站的 del:
#name: del #this program compress a file to the dustbin if test $# -eq 0 then echo "Please specify a file!" else gzip $1 mv $1.gz $HOME/dustbin echo "File $1 is deleted !" fi
test 是 shell 的比較運算子,搭配 if 等條件語句就能做判斷,用法為 test 表達式。
字串比較:= 兩字串相同;!= 不同;-n 長度大於零;-z 長度為零。
數字比較(不用 > 這類符號):-eq 等於、-ge 大於等於、-le 小於等於、-ne 不等於、-gt 大於、-lt 小於。
邏輯運算:! 取反、-a 且、-o 或。
檔案測試(shell 變數都是字串,因此特別提供這類運算子):-d 存在且為目錄、-f 存在且為檔案、-L 為符號連結、-r 可讀、-s 長度非零、-w 可寫、-x 可執行、file1 -nt file2 判斷新舊。
for:
for 變數 in 列表 do 操作 done
變數代表目前處理的項目,列表可以是字串或檔名。
#delete all file with extension of "gz" in the dustbin for i in $HOME/dustbin/*.gz do rm -f $i echo "$i has been deleted!" done
while:條件成立就一直執行。
while 表達式 do 操作 done
until:反過來,執行到條件成立為止。
#add from 1 to 100 total=0 num=0 until test $num -eq 100 do total=`expr $total + $num` num=`expr $num + 1` done echo "The result is $total"
注意那個引號是反引號,代表先執行裡面的命令再取結果。
if 的結束標誌是把 if 反寫成 fi,elif 是 else if 的縮寫,理論上數量不限:
if 表達式1 then 操作 elif 表達式2 then 操作 else 操作 fi
case 用於多分支比對,多個值共用同一段操作時用 | 分隔,每個分支結尾必須兩個分號:
case $USER in
beichen)
echo "You are beichen!";;
liangnian)
echo "You are liangnian";
echo "Welcome!";;
root)
echo "You are root!"; echo "Welcome!";;
*)
echo "Who are you?$USER?";;
esac
基礎就講到這裡。想再往深處走,找一本專門的書慢慢讀,比任何線上片段筆記都靠得住。