Skip to content
Ricky
Chinese

搜尋

Searching… No matching pages. Matching pages are listed below. Search is unavailable. Please try again.

進階 Shell 腳本技巧:用 Bash 自動化複雜任務

  • 則言
  • 2 分鐘
On this page

使用內建指令

減少子殼層

# Inefficient
output=$(cat file.txt)

# Efficient
output=$(<file.txt)

使用陣列處理大量資料

# Inefficient
item1="apple"
item2="banana"
item3="cherry"

# Efficient
items=("apple" "banana" "cherry")
for item in "${items[@]}"; do
    echo "$item"
done

啟用 Noclobber

set -o noclobber

使用函式

高效的檔案操作

# Inefficient
while read -r line; do
    echo "$line"
done < file.txt

# Efficient
while IFS= read -r line; do
    echo "$line"
done < file.txt

平行處理

錯誤處理

# Exit on Error: Using set -e ensures that your script exits immediately if any command fails, preventing cascading errors.
set -e

# Custom Error Messages: Implement custom error messages to provide more context when something goes wrong.
command1 || { echo "command1 failed"; exit 1; }

# Trap Signals: Use the `trap` command to catch and handle signals and errors gracefully.
trap 'echo "Error occurred"; cleanup; exit 1' ERR

function cleanup() {
    # Cleanup code
}

# Validate Inputs: Always validate user inputs and script arguments to prevent unexpected behavior.
if [[ -z "$1" ]]; then
    echo "Usage: $0 <argument>"
    exit 1
fi

# Logging: Implement logging to keep track of script execution and diagnose issues.
logfile="script.log"
exec > >(tee -i $logfile)
exec 2>&1

echo "Script started"

自動化複雜的系統管理工作

  1. 自動化備份
  2. 系統監控
  3. 使用者管理
  4. 自動更新
  5. 網路設定