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

Linux Shell 腳本程式設計完整入門教學

編輯:Linux 教學

Shell 腳本是 Linux 系統管理自動化的核心技能。本文系統整理 Shell 程式設計基礎語法、變數運用、流程控制、常用指令與實戰技巧。

一、腳本基本架構

1.1 Shebang 聲明

腳本首行必須指定解譯器:

#!/bin/bash

#! 告訴系統使用後續路徑的程式執行腳本。常見選項:/bin/bash、/bin/sh。

1.2 執行權限

chmod +x script.sh
./script.sh  # 執行

1.3 註釋語法

# 這是單行註釋
: <<'EOF'
這是多行註釋區塊
支援多行文字說明
EOF

二、變數與環境變數

2.1 變數賦值與引用

# 賦值 (等號兩側不可有空格)
name="Linux"
version=2024

# 引用
echo "Welcome to $name"
echo "Version: ${version}"  # 建議使用大括號避免歧義

2.2 變數名歧義處理

num=2
echo "this is the ${num}nd"  # 正確輸出: this is the 2nd
# echo "this is the $numnd"  # 錯誤: 尋找變數 numnd

2.3 環境變數

export MY_VAR="value"  # 升級為環境變數
env | grep MY_VAR      # 查看環境變數

三、常用 Shell 指令速查

指令功能範例
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

四、流程控制結構

4.1 條件判斷

# 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" ] # 字串相等

4.2 迴圈控制

# 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

4.3 Case 多重選擇

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 -x
  • 錯誤處理: set -e 遇錯即停,trap 'cmd' ERR 捕獲錯誤
  • 輸入重導向: while read line; do ... done < file.txt
  • 管線處理: 善用 |、>、>>、2>&1
Copyright © Windows教程網 All Rights Reserved