Linux Shell Script 實戰
Shell Script 是 Linux 自動化的核心工具,能將重複性工作交給程式處理。
基礎語法
#!/bin/bash
NAME="World"
NAME=$(hostname)
if [ "$NAME" = "server1" ]; then
echo "This is server1"
else
echo "This is $NAME"
fi
for i in {1..5}; do
echo "Count: $i"
done
函式
backup_file() {
local file=$1
local backup_dir="/backup"
cp "$file" "${backup_dir}/$(basename $file).$(date +%Y%m%d)"
echo "Backed up $file"
}
backup_file /etc/nginx/nginx.conf
實用技巧
set -e:遇到錯誤立即退出set -u:使用未定義變數時報錯trap:捕捉信號做清理$?: 上一個指令的退出碼