How to programmatically determine the character sizes of my terminal window?

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

My script has command line arguments for the width and height of the screen (again, as measured in CHARACTERS, not pixels), with the default values ​​being determined by the environment variables of my own invention. I would like these scripts to determine the current window size (IN CHARACTERS) and use THAT as the default value. The typical large window size on my 17-inch Macbook Pro can be 200 x 68.

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

TIA.
Ken

+5
source share
3 answers

The usual way to do this is tput linesand tput cols; these requests to:

  • $LINESand $COLUMNSenvironment variables;
  • termios, which are installed by terminal emulators when resizing their windows;
  • description terminfoidentified $TERM.
+5
source

From C, you should use the parameter TIOCGWINSZfor the system call ioctlon /dev/tty.

This is displayed by the module Term::ReadKey- from man perlfaq8:

How to get screen size?

If you have installed the module Term::ReadKeyfrom CPAN, you can use it to get the width and height in characters and pixels:

use Term::ReadKey;
($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
+2

bash $LINES $COLUMNS. curses/ncurses .

+1
source

All Articles