用 stderr 替换 stdout

mio*_*mio 5 shell io-redirection file-descriptors

是否可以重定向命令的输出以将发送到 stdout 的文本替换为来自 stderr 的文本?

$ ./script
this line is redirected to stdout
this line is redirected to stderr

$ ./script (insert redirections here)
this line is redirected to stderr
Run Code Online (Sandbox Code Playgroud)

我知道我可以只使用1>/dev/null,但我想知道是否有办法将 stderr 中的文本重定向到 stdout。

Mat*_*Mat 7

你可以这样做:

./script 2>&1 1>/dev/null
Run Code Online (Sandbox Code Playgroud)

这会将 fd 2 重定向到 fd 1 指向的内容(即stdout),然后将 fd 1 重定向到/dev/null。第二个重定向不会影响第一个,输出到 fd 2 将被发送到stdout.

顺序确实很重要。有了这个:

./script 1>/dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)

将所有输出发送到/dev/null.