Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curious tput behavior, with stderr redirection

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)"

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

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!

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

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

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

like image 968
danfuzz Avatar asked Feb 13 '14 19:02

danfuzz


1 Answers

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.

like image 109
user2719058 Avatar answered Oct 03 '22 02:10

user2719058