簡體   English   中英

Bash重定向到命令內部

[英]Bash redirection inside command

為什么Bash為這兩個命令產生兩個不同的輸出:

$ echo $(tput cols 2>/dev/null)
80
$ echo $(tput cols)
141

PS。 將您的終端加寬到超過80列(大多數外殼默認為80)。

似乎是因為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

請注意,在您的示例中, $()隱式重定向了stdout。

解決這個問題的方法是

$ max_width=`stty -a | sed -n '/columns/s/.*columns \([^;]*\);.*/\1/p' 2>/dev/null`

瘦身是做您想要的更好的方法!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM