奇怪的输入行为,带有stderr重定向 [英] Curious tput behavior, with stderr redirection

查看:46
本文介绍了奇怪的输入行为,带有stderr重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Bash脚本中使用 tput ,并尽力避免随机错误喷出.为此,我写了以下几行:

I'm trying to use tput in a Bash script, and doing my best to avoid random error spew. To that end, I wrote the following line:

COLS="$(tput cols 2> /dev/null)"

令我惊讶的是,无论我终端窗口的宽度是多少,当我运行此命令时, COLS 始终设置为 80 .(为了演示起见,我的终端刚好是115列宽.)为了弄清楚发生了什么,我在命令行上尝试了一些操作:

To my surprise, when I run this, COLS is consistently set to 80, no matter what the width of my terminal window happens to be. (For the sake of demonstration, my terminal happens to be 115 columns wide.) To figure out what was going on, I tried a few things on the command-line:

$ tput cols
115
$ tput cols | cat
115
$ echo "$(tput cols)"
115
$ tput cols 2> /dev/null
115
$ echo "$(tput cols 2> /dev/null)"
80

因此, tput 似乎在找出其stderr重定向或嵌入到进程替换中时的终端特性方面是成功的,但不能同时解决这两个问题.真奇怪!

So, tput seems to be succeeding in figuring out the terminal characteristics when its stderr is redirected, or when it is embedded in a process substitution, but not both. How odd!

我在Linux和OS X上都进行了测试,其行为是相同的.

I tested this on both Linux and OS X, and the behavior is the same.

这是怎么回事?实际情况是,在抑制stderr喷出的同时使 tput 工作的最佳方法是什么?

What is going on here? And as a practical matter, what's the best way to get tput to work while suppressing stderr spew?

注意:我了解 $ COLUMNS .我对使用 tput 特别感兴趣.

Note: I know about $COLUMNS. I'm specifically interested in using tput.

推荐答案

快速运行 strace 表示 tput 试图确定 stdout ,如果失败,则回退到 stderr .因此,在失败的情况下,两个都将被重定向,并且 tput (显然)假定默认为80列.

A quick strace run suggests that tput tries to determine the terminal width on stdout first, and if that fails, it falls back to stderr. So, in the failing case both are redirected, and tput (apparently) assumes a default of 80 columns.

这篇关于奇怪的输入行为,带有stderr重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆