tree:用树形图查看目录结构
tree 会以树形格式列出目录内容,让项目结构一目了然。
基本用法
tree
按 .gitignore 过滤
一个很实用的功能是按 .gitignore 规则过滤无需追踪的文件:
tree --gitignore
这个选项让 tree 读取 .gitignore 并遵循其中的规则,排除 Git 会忽略的文件和目录。想只看项目中相关的源文件时很方便。
注意: --gitignore 需要 tree 1.8.0 或更新版本。
实用选项
# Limit directory depth
tree -L 2
# Combine with gitignore
tree --gitignore -L 2
# Show only directories
tree -d
tree --gitignore -d
# Include hidden files (except gitignored ones)
tree --gitignore -a
# Show file sizes
tree -s
# Show file permissions
tree -p
# Output in color
tree -C
显示文件和目录大小
tree 提供多种大小显示选项,分析磁盘占用时尤其有用。
以易读的单位显示大小
# Display file sizes and accumulated directory sizes in human-readable format (KB, MB, GB)
tree -h -s
参数含义:
-h:以易读格式打印大小,例如 1.2K、3.5M、2.1G。-s:显示每个文件的大小,对目录则显示其内容累计大小。
输出示例:
.
├── [4.0K] src
│ ├── [2.5K] main.py
│ └── [1.5K] utils.py
├── [1.2M] assets
│ ├── [500K] image1.png
│ └── [700K] image2.png
└── [3.2K] README.md
按大小排序
# Sort files and directories by size (largest first)
tree -h -s --sort=size
--sort=size 按条目的大小排序,方便找出最大的文件与目录。
只显示目录大小
# Display only directories with their accumulated sizes
tree -d -h --du
参数含义:
-d:只列出目录,排除文件。--du:把每个目录中所有文件和子目录的大小累计起来,类似du命令。
输出示例:
.
├── [1.2M] assets
├── [4.0K] src
├── [256K] node_modules
└── [8.0K] config
与其他选项组合
# Show only directories respecting .gitignore, sorted by size
tree -d -h --du --gitignore --sort=size
# Limit depth to 2 levels with sizes
tree -L 2 -h -s
# Show sizes with file permissions
tree -h -s -p
Windows 上的替代方案
注意: Windows 命令提示符自带的 tree 无法显示文件或目录的大小。
Windows 可用的方案:
-
第三方图形工具:
- TreeSize:免费的磁盘空间管理器,可用树形图查看。
- WinDirStat:图形化磁盘使用分析器。
-
PowerShell:
# Custom PowerShell function to display directory tree with sizes Get-ChildItem -Recurse | Select-Object FullName, Length, @{Name="SizeKB";Expression={$_.Length/1KB}} # Or install the PowerTree module Install-Module -Name PowerTree Get-PowerTree -Path . -ShowSize
旧版本的替代办法
如果所用的 tree 不支持 --gitignore,可以尝试:
tree -I "$(cat .gitignore | grep -v '^#' | grep -v '^$' | tr '\n' '|' | sed 's/|$//')"
这会读取 .gitignore,筛掉注释与空行,再把模式转换为 tree 的 -I(忽略)格式。
安装
# Debian/Ubuntu
sudo apt install tree
# CentOS/RHEL
sudo yum install tree
# macOS
brew install tree
grep:显示匹配行上下文
用 grep 搜索日志或源码时,匹配处周围的内容往往正是理解现场所需的线索。grep 的选项可以把匹配行前后的几行一同显示出来。
上下文选项
这些选项在 GNU 和 BSD 版 grep 中都很常见,包括 Linux 和 macOS。
| 选项 | 含义 | 示例 |
|---|---|---|
-A NUM | 打印每处匹配之后的 NUM 行 | grep -A 2 "pattern" filename |
-B NUM | 打印每处匹配之前的 NUM 行 | grep -B 2 "pattern" filename |
-C NUM | 打印每处匹配前后各 NUM 行 | grep -C 2 "pattern" filename |
基本示例
显示匹配之后的行
# Show 3 lines after each match
grep -A 3 "Error" system.log
输出示例:
2025-12-15 10:32:15 Error: Database connection timeout
2025-12-15 10:32:16 Retry attempt 1/3
2025-12-15 10:32:17 Connection still failing
2025-12-15 10:32:18 Retry attempt 2/3
这条命令显示含有 “Error” 的行和紧接它的三行。
显示匹配之前的行
# Show 2 lines before each match
grep -B 2 "Warning" system.log
输出示例:
2025-12-15 10:30:12 Starting backup process
2025-12-15 10:30:13 Reading configuration
2025-12-15 10:30:14 Warning: Backup directory nearly full
这条命令显示含有 “Warning” 的行,以及它之前的两行。
同时显示匹配前后的行
# Show 1 line before and 1 line after each match
grep -C 1 "Critical" system.log
# Or, using -A and -B together (equivalent):
grep -B 1 -A 1 "Critical" system.log
输出示例:
2025-12-15 10:35:20 Security scan running
2025-12-15 10:35:21 Critical: Unauthorized access attempt detected
2025-12-15 10:35:22 Initiating lockdown protocol
-C 1 是同时要求前后各一行的简便写法。
📓 注意: 使用上下文选项时,
grep通常在彼此分开的匹配组之间插入一行--。如果匹配位置足够近,上下文互相重叠,就不会分隔。
让输出更清晰
上下文选项可以搭配其他 grep 参数,提高可读性:
高亮搜索词
# Use --color to visually distinguish the exact match
grep -C 3 --color "pattern" filename
匹配文本会被高亮(通常为红色),在上下文中更容易辨认。
显示行号
# Add -n to show line numbers for all output lines
grep -C 2 -n "pattern" filename
输出示例:
142-2025-12-15 10:30:12 Starting backup process
143-2025-12-15 10:30:13 Reading configuration
144:2025-12-15 10:30:14 Warning: Backup directory nearly full
145-2025-12-15 10:30:15 Available space: 2.3GB
146-2025-12-15 10:30:16 Proceeding with backup
注意匹配行(144)的分隔符是 :,上下文行则用 -。
把增强选项组合起来
# Full example with line numbers, color, and 3 lines of context
grep -C 3 --color -n "pattern" filename
这种组合在调试和分析时能提供最完整的信息。
实际使用场景
排查应用错误
# Find exceptions with surrounding stack trace
grep -A 10 "Exception" app.log
# Find errors with preceding context to see what triggered them
grep -B 5 "ERROR" app.log
分析配置文件
# Find a setting and see related configuration
grep -C 3 "port" /etc/nginx/nginx.conf
搜索源代码
# Find function calls with surrounding code
grep -C 5 "authenticate" src/**/*.py
# Find TODO comments with context
grep -B 2 -A 5 "TODO" src/**/*.js
分析日志
# Find warning patterns with context, highlight matches, show line numbers
grep -C 2 --color -n "timeout\|failed\|error" system.log
# Search multiple files and show which file each match came from
grep -C 3 -n "Exception" *.log
进阶用法
忽略大小写并显示上下文
# Combine -i (ignore case) with context options
grep -i -C 2 "warning" system.log
递归搜索并显示上下文
# Search all files in directory tree with context
grep -r -C 3 "TODO" ./src/
反向匹配并显示上下文
# Show lines NOT matching pattern, with context
grep -v -C 2 "debug" app.log
使用正则表达式并显示上下文
# Use regex patterns with context
grep -E -C 3 "error|warning|critical" system.log
小结
速查时可以记住这条常用命令:
grep -C 3 --color -n "search_term" filename
它会显示:
- 每个匹配行之前和之后各 3 行。
- 彩色高亮的匹配文本。
- 便于跳转定位的行号。
有了这些上下文选项,grep 除了查找文本,还能帮助开发者和系统管理员分析日志、调试代码库。
Bash 输出重定向:同时保存 stdout 和 stderr
问题
尝试把 Docker 日志保存到文件:
docker logs -f container_id > output.txt
终端上可能仍有输出。> 只重定向 stdout。对于未分配 TTY 的容器,Docker 可以保留应用独立的 stdout 和 stderr,CLI 自己的错误也可以写入 stderr。这与是否处于跟随模式无关。使用 TTY 的容器,两个流可能已经合并。
解决办法
使用 &> 同时捕获 stdout 和 stderr:
docker logs -f container_id &> output.txt
这样所有输出都会写入文件。
符合 POSIX 的写法是 > output.txt 2>&1。Docker 特有的日志路径、清理和轮转,见Docker 容器日志管理:查看、导出、清理与轮转。
重定向语法速查
| 语法 | 捕获的内容 |
|---|---|
> file | 仅 stdout |
2> file | 仅 stderr |
&> file | stdout + stderr(Bash 简写) |
> file 2>&1 | stdout + stderr(兼容 POSIX) |
怎样理解这些符号
1= stdout(标准输出),即程序的常规输出。2= stderr(标准错误),用于错误、警告及调试信息。&>里的&表示「两个文件描述符」。2>&1表示「把 stderr(2)重定向到 stdout(1)当前所去的地方」。
更多示例
# Save only errors to a file, show normal output in terminal
docker logs container_id 2> errors.txt
# Save stdout and stderr to separate files
docker logs container_id > output.txt 2> errors.txt
# Discard stderr completely
docker logs container_id 2>/dev/null
# Append instead of overwrite
docker logs container_id &>> output.txt
常见使用场景
# Capture build output including errors
npm run build &> build.log
# Save test results with any error output
pytest &> test_results.txt
# Capture curl response including connection errors
curl https://api.example.com &> response.txt
重定向顺序很重要
shell 从左到右应用重定向。2>&1 复制的是 stdout 当时的目标;stdout 后续改向时,它不会跟着改变。Bash 重定向文档
# Both streams go to output.txt
some_command > output.txt 2>&1
# stderr keeps the original stdout destination (usually the terminal)
some_command 2>&1 > output.txt
> 在命令开始前截断已存在的目标文件,>> 则追加。要追加两个流,使用 some_command >> output.txt 2>&1。Bash 还支持 &>> output.txt。
tee 会复制输入流,echo 不会
Docker 讨论中尝试的管道等价于:
(docker logs -f 8bce > gongkard_log.txt | echo) > 1.txt
显式重定向把 Docker 的 stdout 发往 gongkard_log.txt,覆盖了原本的管道目标。echo 不复制标准输入,没有参数时只打印换行。因此外层重定向收不到 Docker 日志流。加括号能改变分组,改变不了 echo 的行为。
用 tee 把输入复制到文件,并继续输出到 stdout。它默认覆盖指定文件,-a 改为追加。GNU tee 文档
# Save to a file and display in the terminal
docker logs --tail 100 -f 8bce 2>&1 | tee gongkard_log.txt
# Save to two files without displaying the log stream
docker logs --tail 100 -f 8bce 2>&1 | tee gongkard_log.txt > 1.txt
# Append to both files and also display in the terminal
docker logs --tail 100 -f 8bce 2>&1 | tee -a gongkard_log.txt 1.txt
这些导出文件有独立的生命周期。Docker 的日志轮转不会限制它们的大小。
跟随模式不会立即返回退出状态
docker logs -f 会持续输出新增内容。docker logs -f ... && echo Success 中的第二条命令要等第一条成功退出才会运行,不能把它当成启动成功提示。要导出后结束,请去掉 -f,查询一个有限范围。Docker logs 文档
if docker logs --since 30m 8bce > gongkard_log.txt 2>&1; then
printf 'Export completed\n'
else
printf 'Export failed; inspect the output file\n' >&2
fi
在 Bash 中检查管道状态时,set -o pipefail 能让上游错误可见,即使 tee 成功也能发现。它仍不会让正在跟随的命令结束,导出成功也不能证明应用本身健康。Bash 管道文档
参考资料
- Free Software Foundation. (n.d.). Redirections. GNU Bash Reference Manual.
- Free Software Foundation. (n.d.). tee: Redirect output to multiple files or processes. GNU Coreutils Manual.
- Docker. (n.d.). docker container logs. Docker Docs. Retrieved November 13, 2026.
- Free Software Foundation. (n.d.). Pipelines. GNU Bash Reference Manual.