命令中的Bash重定向

Nik*_*tur 2 bash

为什么Bash为这两个命令生成两个不同的输出:

$ echo $(tput cols 2>/dev/null)
80
$ echo $(tput cols)
141
Run Code Online (Sandbox Code Playgroud)

PS.扩展您的终端有超过80列(大多数shell默认为80).

Gor*_*son 5

这似乎是因为stdout和stderr都被重定向,所以tput不知道你想要什么终端信息.

$ tput cols >out; cat out       # works because stderr is still the terminal
118
$ tput cols 2>err               # works because stdout is still the terminal
118
$ tput cols >out 2>err; cat out # lost track of the terminal, going with default
80
Run Code Online (Sandbox Code Playgroud)

请注意,在您的示例中,stdout被隐式重定向$().