Shell:bash脚本入门
Shell入门 – The Missing Semester of Your CS Education
一、Shell脚本基础
1.1 变量与字符串
# 正确赋值(无空格)
foo=bar
# 错误示例(带空格会报错)
foo = bar
# 双引号支持变量扩展
echo "Value: $foo" # 输出 Value: bar
# 单引号保持原样
echo 'Value: $foo' # 输出 Value: $foo
1.2 特殊变量
| 变量 | 描述 |
|---|---|
$0 | 脚本名称 |
$1-$9 | 第1-9个参数 |
$@ | 所有参数 |
$? | 前命令退出码 |
$$ | 当前进程PID |
!! | 完整上条命令 |
$_ | 上条命令末参数 |
1.3 控制流与函数
# if条件判断
if [[ $? -ne 0 ]]; then
echo "Command failed"
fi
# 带参数的函数示例
mcd() {
mkdir -p "$1"
cd "$1"
}
1.4 退出码与逻辑操作
false || echo "Oops" # 输出 Oops
true && echo "Success" # 输出 Success
false ; echo "Always Run" # 输出 Always Run
1.5 高级技巧
命令替换:
for file in $(ls)
进程替换:
diff <(ls dir1) <(ls dir2)
通配符扩展:
convert image.{png,jpg} # 展开为两个文件
touch {a..c}.txt # 创建 a.txt b.txt c.txt
二、高效Shell工具
2.1 文件搜索三剑客
| 工具 | 特点 | 示例 |
|---|---|---|
find | 功能强大,支持复杂条件 | find . -name "*.log" -mtime -7 |
fd | 更快的替代品,友好语法 | fd ".*py$" |
locate | 基于数据库,速度快但非实时 | locate config.yml |
2.2 代码搜索利器
# 基本grep用法
grep -R "TODO" src/
# ripgrep高级用法
rg -t py "import requests" # 搜索Python文件
rg foo -A5 -B3 # 显示匹配前后上下文
2.3 历史命令管理
Ctrl+R:反向搜索历史命令history | grep ssh:过滤特定命令fzf:模糊查找历史命令
2.4 目录导航神器
z projects # fasd快速跳转
j downloads # autojump跳转
broot # 可视化目录树
三、实用脚本范例
3.1 自动添加文件标记
#!/bin/bash
for file in "$@"; do
grep -q "TODO" "$file" || echo "# TODO" >> "$file"
done
3.2 错误重试脚本
#!/bin/bash
count=0
until [[ $? -ne 0 ]]; do
./buggy_script.sh &>> output.log
((count++))
done
echo "Failed after $count runs"
3.3 HTML文件打包
# Linux
find . -name "*.html" -print0 | xargs -0 tar -czf html_files.tar.gz
# MacOS
find . -name "*.html" -print0 | xargs -0 gtar -czf html_files.tar.gz
四、高频使用技巧
4.1 文档查询
man ls # 官方手册
tldr tar # 快速示例
4.2 文件批处理
# 批量重命名
rename 's/.JPG/.jpg/' *.JPG
# 并行处理
find . -name "*.log" | parallel gzip
4.3 安全防护
# 防止误删
alias rm="rm -i"
# 敏感操作记录
HISTCONTROL=ignorespace # 空格开头的命令不记入历史
五、课后练习精要
-
ls命令大师
ls -lah --color=auto --sort=time -
目录书签系统
# marco.sh marco() { echo "$PWD" > /tmp/marco.dir; } polo() { cd "$(cat /tmp/marco.dir)"; } -
随机错误捕获
使用until循环结合输出重定向 -
HTML压缩专家
结合find与xargs处理含空格文件名 -
(进阶)最近文件追踪
find . -type f -printf "%T+ %p\n" | sort -r | head -n 10