Shell 腳本是 Linux 系統管理自動化的核心技能。本文系統整理 Shell 程式設計基礎語法、變數運用、流程控制、常用指令與實戰技巧。
腳本首行必須指定解譯器:
#!/bin/bash
#! 告訴系統使用後續路徑的程式執行腳本。常見選項:/bin/bash、/bin/sh。
chmod +x script.sh
./script.sh # 執行
# 這是單行註釋
: <<'EOF'
這是多行註釋區塊
支援多行文字說明
EOF
# 賦值 (等號兩側不可有空格)
name="Linux"
version=2024
# 引用
echo "Welcome to $name"
echo "Version: ${version}" # 建議使用大括號避免歧義
num=2
echo "this is the ${num}nd" # 正確輸出: this is the 2nd
# echo "this is the $numnd" # 錯誤: 尋找變數 numnd
export MY_VAR="value" # 升級為環境變數
env | grep MY_VAR # 查看環境變數
| 指令 | 功能 | 範例 |
|---|---|---|
| echo | 輸出文字 | echo "Hello World" |
| ls | 列出檔案 | ls -la |
| wc | 統計行/字/字元數 | wc -l file.txt |
| cp | 複製檔案 | cp src dest |
| mv | 移動/重命名 | mv old new |
| rm | 刪除檔案 | rm -f file |
| grep | 搜尋字串 | grep 'pattern' file |
| cut | 擷取欄位 | cut -b5-9 file.txt |
| cat | 顯示檔案內容 | cat file.txt |
| file | 判斷檔案類型 | file image.png |
| read | 讀取使用者輸入 | read var |
| sort | 排序 | sort file.txt |
| uniq | 去除重複行 | sort file.txt | uniq |
| expr | 數學運算 | expr 2 + 3 |
| find | 搜尋檔案 | find . -name "*.sh" |
| tee | 雙向輸出 | cmd | tee log.txt |
# if-else 結構
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
# 測試運算子
[ -f file ] # 檔案存在且為一般檔案
[ -d dir ] # 目錄存在
[ -r file ] # 可讀
[ -w file ] # 可寫
[ -x file ] # 可執行
[ $a -eq $b ] # 數值相等
[ "$a" = "$b" ] # 字串相等
# for 迴圈
for i in 1 2 3; do
echo $i
done
for file in *.txt; do
echo "Processing $file"
done
# while 迴圈
while [ condition ]; do
commands
done
# until 迴圈 (條件為真時結束)
until [ condition ]; do
commands
done
case $var in
pattern1) commands ;;
pattern2) commands ;;
*) default_commands ;;
esac
my_function() {
local param1=$1
local param2=$2
echo "Parameters: $param1, $param2"
return 0
}
my_function "arg1" "arg2"
bash -x script.sh 或腳本加入 set -xset -e 遇錯即停,trap 'cmd' ERR 捕獲錯誤while read line; do ... done < file.txt|、>、>>、2>&1