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
As I mentioned in lyceus answer, his code will fail on non-English locale Windows because then the output of
mode
may not contain the substrings "columns" or "lines":You can find the correct substring without looking for text:
Note that I'm not even bothering with lines because it's unreliable (and I actually don't care about them).
Edit: According to comments about Windows 8 (oh you...), I think this may be more reliable:
Do test it out though, because I didn't test it.
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)On POSIX, ultimately you want to be invoking the
TIOCGWINSZ
(Get WINdow SiZe)ioctl()
call. Most languages ought to have some sort of wrapper for that. E.g in Perl you can use Term::Size:Inspired by @pixelbeat's answer, here's a horizontal bar brought to existence by
tput
, slight misuse ofprintf
padding/filling andtr
And there's
stty
, from coreutilsIt will print the number of rows and columns, or height and width, respectively.
Then you can use either
cut
orawk
to extract the part you want.That's
stty size | cut -d" " -f1
for the height/lines andstty size | cut -d" " -f2
for the width/columnsThere are some cases where your rows/LINES and columns do not match the actual size of the "terminal" being used. Perhaps you may not have a "tput" or "stty" available.
Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.