As noted by choroba in a comment, you can find the terminal size in shell scripts using stty size
.
This works on Linux, and also on macOS (Monterey 12.6.6 tested), and by inference on BSD-based platforms. It is not mandated by POSIX 2018 AFAICT. It prints the screen size as "rows cols" (two numbers separated by white space).
For example, when run in a rather large window (with 65 rows by 207 columns) on a big screen, I got the output:
$ stty size
65 207
$
On both Linux and macOS, stty
objects if standard input is not a terminal and writes an error message to standard error (even if, for example, standard error is connected to a terminal). You can work around that with -F /dev/stderr
(or another named file) if need be, but you'll still get an error if ioctl(fd, TIOCGWINSZ, &winsz)
fails. You may actually find a use for the shell test operator [ -t 0 ]
(or 1
or 2
) — which tests whether the numbered file descriptor is a terminal.
A deleted answer by hek2gml mentions that you can use:
$ tput lines
65
$ tput cols
207
$
You can only get one number at a time.