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

Shell Scripting 基礎入門指南:從 Shell 類型到第一支腳本

編輯:Linux 教學

什麼是 Shell?

Shell 是 Unix-like 作業系統的命令解譯器。它接收使用者輸入的指令,呼叫核心執行。簡單說,Shell 是作業系統的包裝層,提供人機介面。

$ ls
config  data  pam  test

$ 是 Shell 提示符,表示等待輸入。輸入 ls 並按 Enter,Shell 解析指令並執行。

Shell 提示符

  • $:一般使用者
  • #:root 使用者
  • 可自訂 PS1 環境變數修改提示符外觀

常見 Shell 類型比較

Shell路徑特色預設環境
Bourne Shell (sh)/bin/sh原始 Unix Shell,功能最基本所有 Unix-like
C Shell (csh)/bin/csh語法類 C 語言,支援歷史指令回顧BSD 系統
Korn Shell (ksh)/bin/ksh兼容 sh,加入陣列、函數等進階功能AIX, HP-UX
Bash (Bourne Again Shell)/bin/bash整合 ksh、csh 優點,功能最豐富Linux, macOS
Tcsh/bin/tcshcsh 增強版,支援命令列編輯、Tab 自動完成部分 Linux

什麼是 Shell Script?

包含一或多條指令的文字檔案。Shell 逐行讀取並執行,如同在終端機手動輸入。

為什麼使用 Shell Script?

  • 自動化系統管理任務
  • 封裝複雜配置細節
  • 組合指令建立新工具
  • 整合圖形介面與命令列優勢

建立第一支腳本

步驟 1:建立檔案

#!/bin/bash
# Written by LinuxTechi
pwd
date
  • #!/bin/bash:Shebang,指定解譯器
  • #:註解

步驟 2:賦予執行權限

chmod +x myscript.sh

步驟 3:執行腳本

./myscript.sh
# 或
bash myscript.sh

互動式輸入處理

#!/bin/bash
echo 'What is Your Name?'
read name
echo "My Name is, $name"
$ ./myscript.sh
What is Your Name?
Linuxtechi
My Name is, Linuxtechi

核心概念總結

  1. Shell 是指令解譯器,連接使用者與核心
  2. Bash 是 Linux 最常見的預設 Shell
  3. Shell Script 將指令序列化、自動化
  4. read 讀取使用者輸入,echo 輸出結果
  5. 變數引用使用 $var 或 ${var}

後續學習路徑

  • 變數與資料型別
  • 條件判斷 (if/case) 與迴圈 (for/while)
  • 函數與模組化
  • 字串處理與正則表達式
  • 除錯技巧 (set -x, bash -x)
  • 進階工具:awk, sed, grep

Shell Scripting 是 Linux 系統管理與 DevOps 的核心技能,從基礎開始扎實練習,將獲得極高的投資報酬率。

Copyright © Windows教程網 All Rights Reserved