How do I find the width & height of a terminal window?

As a simple example, I want to write a CLI script which can print = across the entire width of the terminal window.

#!/usr/bin/env php
<?php
echo str_repeat('=', ???);

or

#!/usr/bin/env python
print '=' * ???

or

#!/usr/bin/env bash
x=0
while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo

  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.

In bash, the $LINES and $COLUMNS environmental variables should be able to do the trick. The will be set automatically upon any change in the terminal size. (i.e. the SIGWINCH signal)


And there's stty, see stty: Print or change terminal characteristics, more specifically Special settings

$ stty size
60 120 # <= sample output

It will print the number of rows and columns, or height and width, respectively.

Then you can use either cut or awk to extract the part you want.

That's stty size | cut -d" " -f1 for the height/lines and stty size | cut -d" " -f2 for the width/columns