Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

30 分鐘快速入門 Shell 腳本程式設計:從 Hello World 到自動化腳本

編輯:Linux 教學

什麼是 Shell 腳本?

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

執行環境準備

作業系統支援

  • Linux:預裝 Bash/Sh
  • macOS:內建 sh、bash、zsh、ksh 等
  • Windows:需安裝 Cygwin、MSYS2 或 WSL 模擬環境

常見解釋器

解釋器路徑備註
Bourne Shell (sh)/bin/shPOSIX 標準,移植性最佳
Bash/bin/bashGNU 專案,功能最豐富,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 多重分支

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 相容寫法

常用文字處理三劍客

  • grep:模式搜尋
  • awk:欄位切割與運算
  • sed:串流編輯(增刪改)

搭配管道 | 可構建強大資料處理管線,如 ps aux | grep nginx | awk '{print $2}' | xargs kill。


掌握上述核心語法,即可開始撰寫備份、部署、監控等自動化腳本。建議實作練習:編寫一支腳本每日備份 /etc 並上傳至遠端伺服器,體驗 Shell 腳本的實戰威力。

Copyright © Windows教程網 All Rights Reserved