首行必須為 #!/bin/sh,告知系統用什麼解釋器執行。賦予執行權限:chmod +x filename,以 ./filename 執行。
以 # 開頭至行尾為註釋,建議養成習慣,利於維護。
所有變量皆為字串,無需聲明。賦值:a="hello world"。引用:echo $a 或 echo ${a}。
變量名邊界模糊時用花括號:num=2; echo "this is the ${num}nd" → 輸出 this is the 2nd。
export 處理過的變量為環境變量,通常用於登入腳本。
腳本中可用三類命令:
| 命令 | 功能 |
|---|---|
| echo "text" | 輸出文字 |
| ls | 列出檔案 |
| wc -l/-w/-c file | 統計行/字/字元數 |
| cp src dst | 複製檔案 |
| mv old new | 重命名/移動 |
| rm file | 刪除檔案 |
| grep 'pattern' file | 搜尋字串 |
| cut -b 5-9 file | 擷取第 5-9 字元 |
| cat file | 輸出檔案內容 |
| file somefile | 查看檔案型別 |
| read var | 互動輸入賦值 |
| sort file | 排序行 |
| uniq | 去除重複行 |
| expr 2 + 3 | 數學運算 |
| find . -name f -print | 依名稱尋檔 |
| tee outfile | 同時輸出螢幕與檔案 |
| basename /dir/file | 取檔名 |
| dirname /dir/file | 取目錄路徑 |
| head/tail file | 顯示開頭/結尾幾行 |
| sed 's/old/new/' | 正則替換 |
| awk -F, '{print $1,$3}' | 欄位擷取 |
grep "hello" file.txt | wc -ltar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print` 打包 24 小時內修改過的檔案。if [ condition ]; then
...
elif [ condition ]; then
...
else
...
fi
常用測試運算子(方括號內兩側須有空格):
[ -f "file" ] 是否為檔案[ -x "/bin/ls" ] 存在且可執行[ -n "$var" ] 變數非空[ "$a" = "$b" ] 字串相等執行 man test 查看完整列表。
if [ "$SHELL" = "/bin/bash" ]; then
echo "your login shell is bash"
else
echo "your login shell is $SHELL"
fi
&&:左真執行右。[ -f /etc/shadow ] && echo "uses shadow passwords"||:左假執行右。[ -r "$mailfolder" ] || { echo "Cannot read $mailfolder"; exit 1; }case $var in
pattern1) commands ;;
pattern2) commands ;;
*) default_commands ;;
esac
select var in option1 option2 option3; do
case $var in
option1) ... ;;
option2) ... ;;
option3) ... ;;
esac
done
自動生成編號選單,輸入編號執行對應區塊,輸入空行重顯選單,Ctrl+D 結束。
for var in list; do commands; done
# 例:for i in 1 2 3; do echo $i; done
while [ condition ]; do commands; done
until [ condition ]; do commands; done
同其他語言,跳出或跳過本次迴圈。
func_name() {
commands
return value
}
func_name arg1 arg2
函數內用 $1, $2 取參數,$# 參數個數,$@ 所有參數。
掌握 Shebang、變量、常用命令、管道重導向、條件判斷、迴圈與函數,即可編寫實用的自動化腳本。建議多實作、多查 man 手冊。