Unix Shell 脚本入门指南
一 环境准备与第一个脚本
#!/bin/bash
# 第一个 Shell 脚本
echo "Hello, $USER!"
chmod +x hello.sh # 添加可执行权限
./hello.sh # 执行脚本
bash hello.sh # 直接用 bash 解释器运行(无需 +x)
source hello.sh # 或 . hello.sh,在当前 Shell 中执行
二 核心语法速览
name="Alice"
echo "Hello, $name" # 变量引用
readonly PI=3.14 # 只读变量
arr=(a b c) # 数组
echo "${arr[1]}" # 数组下标从 0 开始
read -p "Name: " name
echo "Hi, $name"
if [ -f "$file" ]; then
echo "$file exists."
elif [ -d "$file" ]; then
echo "$file is a directory."
else
echo "$file not found."
fi
# for 遍历通配符更安全(避免 for f in $(ls *.txt) 的陷阱)
for f in *.txt; do
[ -e "$f" ] || continue # 若无匹配文件,防止字面量 *.txt 被处理
echo "Processing $f"
done
# while 计数
i=1
while [ $i -le 5 ]; do
echo "$i"
((i++))
done
greet() {
local name="$1" # 局部变量
echo "Hello, $name"
}
greet "Bob"
# 统计 .sh 文件行数
find . -name "*.sh" -type f | xargs wc -l
# 日志追加
echo "[$(date)] Start" >> app.log 2>&1
三 实战示例 日志分析小工具
#!/usr/bin/env bash
# 用法:./logerr.sh <日志文件> [关键字=ERROR] [top=N]
set -euo pipefail # 严格模式:遇错退出、未定义变量报错、管道错误传播
file="${1:-}"
keyword="${2:-ERROR}"
top="${3:-5}"
if [ ! -f "$file" ]; then
echo "Usage: $0 <log-file> [keyword=ERROR] [top=N]" >&2
exit 1
fi
echo "=== $keyword count ==="
grep -i "$keyword" "$file" | wc -l
echo -e "\n=== Top $top $keyword lines ==="
grep -i "$keyword" "$file" \
| sed 's/^\([^ ]\{1,\} [^ ]\{1,\} [^ ]\{1,\}\) .*/\1/' \
| sort \
| uniq -c \
| sort -nr \
| head -n "$top" \
| sed 's/^ *\([0-9]\+\) /\1: /'
chmod +x logerr.sh
./logerr.sh app.log ERROR 10
四 调试与最佳实践
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。