Skip to main content
2 of 4
added 194 characters in body
Stéphane Chazelas
  • 574.5k
  • 96
  • 1.1k
  • 1.6k

tput cols and tput rows query the size of the terminal (from the terminal device driver, not the terminal itself) from the terminal device on stdout, and if stdout is not a terminal device like in the case of cols=$(tput cols) where it's then a pipe, from stderr.

So, to retrieve the values from an arbitrary terminal device, you need to open that device on the stderr of tput:

{ cols=$(tput cols) rows=$(tput rows); } 2< "$TERMINAL"

(here open in read-only mode so tput doesn't output its error messages there).

Alternatively, you may be able to use stty size. stty queries the terminal on stdin:

read rows cols < <(stty size < "$TERMINAL")

None of those are standard so may (and in practice will) not work on all systems. It should be fairly portable to GNU/Linux systems though.

The addition of stty size or other method to query terminal size was requested to POSIX but the discussion doesn't seem to be going anywhere.

Stéphane Chazelas
  • 574.5k
  • 96
  • 1.1k
  • 1.6k