Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 988
Ken Avatar asked Apr 22 '11 19:04

Ken


2 Answers

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.
like image 135
geekosaur Avatar answered Sep 24 '22 21:09

geekosaur


From C, you'd use the TIOCGWINSZ option to an ioctl system call on /dev/tty.

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

How do I get the screen size?

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

use Term::ReadKey;
($wchar, $hchar, $wpixels, $hpixels) = GetTerminalSize();
like image 36
Alnitak Avatar answered Sep 21 '22 21:09

Alnitak