Search code examples
perlbashscriptingterminalterminal-emulator

How to programmatically determine character dimensions of my terminal window?


I am writing a script which will display a stock chart as ASCII art in a terminal emulator window. I normally use OSX/Terminal.app but a Linux-based solution would be an acceptable alternative.

My script currently has command-line args for screen width and height (again, as measured in CHARACTERS, not pixels), with defaults determined by environment variables of my own invention. I would like these scripts to determine the current window's size (IN CHARACTERS), and use THAT as the default. A typical size for a big window on my 17-inch Macbook Pro might be 200 x 68.

This is a perl script, but if you know a solution in some other language, do tell!

TIA.
Ken


Solution

  • The usual way to do this is tput lines and tput cols; this queries, in order:

    • $LINES and $COLUMNS environment variables;
    • termios settings, which are set by terminal emulators when you resize their windows;
    • the terminfo description identified by $TERM.