Shell 是提供使用者與作業系統核心互動的介面程式,分為圖形介面(如 Windows Explorer)與命令列介面(如 Bash、Zsh)。Shell Script(殼層腳本)則是為 Shell 撰寫的解釋執行程式碼,副檔名慣用 .sh。
#!/bin/sh
cd ~
mkdir shell_tut
cd shell_tut
for ((i=0; i<10; i++)); do
touch test_$i.txt
done
逐行解析:
#!/bin/sh:指定解釋器路徑(shebang)cd ~:切換至家目錄mkdir shell_tut:建立目錄for ((i=0; i<10; i++)):C 風格迴圈跑 10 次touch test_$i.txt:建立 test_0.txt ~ test_9.txt| 解釋器 | 路徑 | 備註 |
|---|---|---|
| Bourne Shell (sh) | /bin/sh | POSIX 標準,移植性最佳 |
| Bash | /bin/bash | GNU 專案,功能最豐富,Linux 預設 |
| Zsh | /bin/zsh | 擴充性強,Oh My Zsh 熱門框架 |
注意:CentOS 中 /bin/sh 指向 bash,但 macOS 上兩者為獨立二進位檔。
your_name="qinjx" # 定義(等號兩旁不可有空格)
echo $your_name # 使用
echo ${your_name} # 建議加花括號界定邊界
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo ${#string} # 字串長度
echo ${string:1:4} # 子字串(索引 1 起長度 4)
if [ $foo -eq 0 ]; then
command1
elif [ $foo -gt 0 ]; then
command2
else
command3
fi
關鍵點: [ 實為 /usr/bin/[ 可執行檔,方括號與條件式必須以空格分隔。
# for 列表
for var in item1 item2; do
command
done
# C 風格 for
for ((i=0; i<10; i++)); do
command
done
# while
while condition; do
command
done
# 無限迴圈
while true; do command; done
case "${opt}" in
"Install-Server") install_master ;;
"Install-Client") install_client ;;
*) echo "Bad option" ;;
esac
# 定義
my_func() {
local param=$1
echo "Param: $param"
return 0
}
# 呼叫
my_func "argument"
source ./function.sh
# 或
. ./function.sh # POSIX 相容寫法
搭配管道 | 可構建強大資料處理管線,如 ps aux | grep nginx | awk '{print $2}' | xargs kill。
掌握上述核心語法,即可開始撰寫備份、部署、監控等自動化腳本。建議實作練習:編寫一支腳本每日備份 /etc 並上傳至遠端伺服器,體驗 Shell 腳本的實戰威力。