使用>或1>重定向标准输出,2>重定向标准错误;2. 分离输出:command > output.log 2> error.log可将正常输出和错误分别保存;3. 合并输出推荐command > all.log 2>&1,确保输出顺序一致;4. 丢弃输出可用/dev/null,如command > /dev/null 2>&1完全静默;5. 管道中处理错误需先合并:command 2>&1 | grep "error";6. 使用tee同时显示并保存:command 2>&1 | tee output.log。关键是理解文件描述符1和2的独立性,且2>&1必须紧跟在>之后生效,顺序错误会导致重定向失败,正确顺序为> file 2>&1,最终实现清晰的输出管理。

在 Linux 中,正确处理标准输出(stdout)和标准错误输出(stderr)是编写脚本或调试命令时的常见需求。通过重定向,你可以将正常输出和错误信息分别保存到不同文件,或者统一处理,避免信息混杂。以下是标准输出和错误流的分离与重定向方法。
>
1>
2>
&>
>&
|
如果你想把正常输出和错误信息分别保存到不同的文件,可以这样写:
command > output.log 2> error.log
>
output.log
2>
error.log
例子:
ls /existent /nonexistent > found.txt 2> not_found.txt
found.txt
not_found.txt
如果你希望把 stdout 和 stderr 都写入同一个文件,有几种写法:
command > all.log 2> all.log
⚠️ 注意:这可能导致输出交错或覆盖,因为两个流同时写入同一个文件。
command > all.log 2>&1
>
1>
all.log
2>&1
all.log
✅ 这是推荐做法,输出顺序一致,内容完整。
有时候你只关心其中一种输出,可以重定向到
/dev/null
只保留错误,忽略正常输出:
command > /dev/null 2> error.log
只保留正常输出,忽略错误:
command > output.log 2> /dev/null
完全静默(不显示任何输出):
command > /dev/null 2>&1
或简写为:
command &> /dev/null
默认情况下,
|
command 2>&1 | grep "error"
2>&1
grep
这样即使错误信息也能被
grep
使用
tee
command 2>&1 | tee output.log
output.log
若想分别处理 stdout 和 stderr 并使用 tee,可以这样:
command > >(tee output.log) 2> >(tee error.log >&2)
这使用了进程替换(process substitution),适合复杂场景。
基本上就这些常用方式。关键是理解文件描述符 1(stdout)和 2(stderr)的独立性,以及
2>&1
>
> file 2>&1
2>&1 > file
以上就是如何重定向Linux输出 标准输出错误流分离的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号