因此,我正在编写脚本,发现了一些奇怪的行为。我敢肯定有一个合理的解释,为什么4的输出日和6日的命令行比在其他情况不同,但我无法找到它。
1 $ tput cols
128
2 $ tput cols 2>/dev/null
128
3 $ echo $(tput cols)
128
4 $ echo $(tput cols 2>/dev/null)
80
5 $ (tput cols >/tmp/cols.txt); cat /tmp/cols.txt
128
6 $ (tput cols &>/tmp/cols.txt); cat /tmp/cols.txt
80
7 $ echo $(tput cols 2>/dev/null; echo $COLUMNS; tput cols)
80 128 128
为什么stderr重定向会在子shell中更改tput的输出?
最终,我想在脚本中执行以下操作,以使其在无法使用tput / ncurses的系统上运行:
cols=$(tput cols 2>/dev/null || echo $COLUMNS)
上面的示例是使用Bash 4.3.46(1)-release和ncurses 6.0.20150627创建的
根据strace
,发生这种情况是因为tput
仅尝试从其stdout和stderr(fd 1&2)读取tty设置。由于您已经显式重定向了stderr,并且$( )
还重定向了stdout,因此tput放弃了。
最好的解决办法是打补丁tput以便还检查stdin中是否存在tty。但是,您也可以只删除2>/dev/null
重定向,因为tput cols
无论如何永远不会输出任何错误消息。(并且如果确实输出了一些错误消息,则最好注意它们。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句