Nikola Kotur
Nikola Kotur

Reputation: 1994

Bash redirection inside command

Why is Bash producing two different outputs for these two commands:

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

PS. Widen your terminal to have more than 80 columns (most shells default to 80).

Upvotes: 2

Views: 272

Answers (2)

JonatasTeixeira
JonatasTeixeira

Reputation: 1492

A way to solve this problem is

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

stty is better way to do what you want!

Upvotes: 1

Gordon Davisson
Gordon Davisson

Reputation: 125788

It appears to be because both stdout and stderr have been redirected, so tput doesn't know what terminal you want the info for.

$ 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

Note that in your example, stdout is redirected implicitly by $().

Upvotes: 5

Related Questions