如何在 Bash 中将 Stderr 重定向到 Stdout

介绍

将命令的结果发送到文件或其他命令时,您可能会看到屏幕上显示错误消息通知。

在 Bash 和其他 Linux shell 中,有 3 个标准 I/O 流。 每个流都有不同的数字 id:

0 – 标准输入:输入流。

1-标准输出:输出流。

2 – stderr:错误流。

本文将向您展示如何在 Bash 中将 stderr 重定向到 stdout,如下所述。

重定向输出

重定向是预先知道一个程序的输出并将命令的结果发送到文件或另一个命令的方法。

语法:

$ command n> file

n:流的数字 id

如果命令没有 n,则默认值为 1-stdout。

为了 example,我想将 ls 的输出发送到 ls.txt 文件:

$ ls > ls.txt

然后我使用 cat 命令检查输出:

$ cat ls.txt

输出:

我们可以将 1-stdout 与 2-stderr 结合起来:

$ command 1> file 2> file

为了 example:

$ ls /home 1> stdout.txt cat big.txt 2> stderr.txt

使用 cat 命令检查:

$ cat stdout.txt

输出:

$ cat stderr.txt

输出:

错误消息,因为 big.txt 文件不存在。

将标准错误重定向到标准输出

语法:

$ command > file 2>&1

其他方式:

$ command &> file

在 Bash 中,&> 用于替换 2>&1:

为了 example,我将cat big.txt的错误信息发送到error.txt文件中:

$ cat big.txt > error.txt 2>&1

使用 cat 命令检查:

$ cat error.txt

输出:

结论

您刚刚看到了有关如何在 Bash 中将 stderr 重定向到 stdout 的详细说明。

感谢您的阅读。