442

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
2

10 Answers 10

802
  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.
Sign up to request clarification or add additional context in comments.

echo -e "lines\ncols"|tput -S to get both the lines and cols see: linux.about.com/library/cmd/blcmdl1_tput.htm
@nickl tput lines cols gets the same output, that is both the lines and columns, at least on Ubuntu 24.04.1 LTS.
tput is a great command with lots of commands for reading the state of the terminal, controlling the cursor and text properties, and so on.
Handy alias, for example: alias dim="echo $(tput cols)x$(tput lines)", which might result in 80x50.
This Q&A probably belongs on either the unix or superuser SE sites.
@bishop the alias command you provided gets evaluated when the shell gets sourced. You need to use single quotes for the alias command. Like so: alias dim='echo Terminal Dimensions: $(tput cols) columns x $(tput lines) rows'
149

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)

However, these environment variables are only available to bash, and not to any programs that run inside bash (like perl, python, ruby).
That does not work in anything but the interactive bash session (if you run the script it is not interactive any longer). The only place you can use it in a script is the prompt_command in bash.
Actually, it does work in non-interactive scripts, if you set the checkwinsize option. For example, this non-interactive script will print the dimensions of the terminal on which it is run : shopt -s checkwinsize; (:); echo $LINES $COLUMNS (the checkwinsize option only initializes the variables after waiting for a subshell to finish, which is why we need the (:) statement)
LINES and COLUMNS are only set as shell variables by bash. Bash will not set them as environment variables, unless you export these shell variables.
@Br.Bill COLUMNS and LINES are defined by POSIX, they have nothing to do with bash and nowhere is defined, that its the task of the shell to set them. POSIX says that the user can set them to desired values: pubs.opengroup.org/onlinepubs/9699919799/basedefs/…
123

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

$ stty size
60 120 # <= sample output

# To read into variables, in bash
$ read -r rows cols < <(stty size)
$ echo "rows: $rows, cols: $cols"
rows: 60, cols: 120

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

Or 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

This style cannot work with PIPE, suggest use tput style.
the problem with tput is that it is not always available while stty is available in every tty. thanks for that info!
stty is not from coreutils. stty is POSIX standard and thus pretty much available everywhere, also on BSD systems that definitely won't have coreutil Coreutils just implements the majority of the POSIX terminal standard.
While stty(1) is defined by POSIX, the argument size is not.
As opposed to the version 1003.1-2017, newer version of POSIX, 1003.1-2024, does indeed define the parameter size.
24
yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'

Not a direct answer to the question, but a great demo script.
What a great example!
how the heck did I miss the tr command all these years? (facepalm)
yes '=' will output an infinite amount of '=' lines and the following commands organize enough to fill the terminal
Nice example; if you want a bashism even more cryptic: eval printf '=%.0s' {1..$[$COLUMNS*$LINES]}.
12

To do this in Windows CLI environment, the best way I can find is to use the mode command and parse the output.

function getTerminalSizeOnWindows() {
  $output = array();
  $size = array('width'=>0,'height'=>0);
  exec('mode',$output);
  foreach($output as $line) {
    $matches = array();
    $w = preg_match('/^\s*columns\:?\s*(\d+)\s*$/i',$line,$matches);
    if($w) {
      $size['width'] = intval($matches[1]);
    } else {
      $h = preg_match('/^\s*lines\:?\s*(\d+)\s*$/i',$line,$matches);
      if($h) {
        $size['height'] = intval($matches[1]);
      }
    }
    if($size['width'] AND $size['height']) {
      break;
    }
  }
  return $size;
}

I hope it's useful!

NOTE: The height returned is the number of lines in the buffer, it is not the number of lines that are visible within the window. Any better options out there?

Note a problem with this: the output of this command is locale-specific. In other words, this will not work as-is on another Windows locale. This is what I get on Windows 7: i.imgur.com/Wrr7sWY.png
Added an answer with a solution to that. +1 though!
11

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:

use Term::Size qw( chars );

my ( $columns, $rows ) = chars \*STDOUT;

Thanks for this – led me in the right direction. Elixir: :io.columns Erlang: io:columns(). erlang.org/doc/man/io.html#columns-0
There's no TIOCGWINSZ in the POSIX standard and ioctl() is only defined for the obsolescent STREAMS feature.
6

Inspired by @pixelbeat's answer, here's a horizontal bar brought to existence by tput, slight misuse of printf padding/filling and tr

printf "%0$(tput cols)d" 0|tr '0' '='

Comments

5

Getting the window width

Make a global variable $termsize track the size of the terminal window:

settermsize() {
    termsize="$(stty size 2>/dev/null)" && [ "$termsize" ] ||
        termsize='25 80'
}
trap settermsize WINCH
settermsize

If stty size fails, the above code assumes that the terminals 80 columns wide and 25 lines high. POSIX does not mandate the size operand for stty, so the fallback is needed.

You can then access the columns argument by using the shell's string substitution capabilities:

echo "${termsize% *}" # Prints the terminal's height.
echo "${termsize#* }" # Prints the terminal's width.

Of course, the scripting language you use likely offers a library that takes care of that for you -- and you should use it.

Printing a line

Once you know the width of the terminal, printing a horizontal line is easy, for example, by abusing printf's string padding:

printf '%*s\n' "${termsize#* }" '' | 
tr ' ' -

The first line tells printf to print as many spaces as there are columns (by abusing string padding) to a pipe.

The second line tells tr to read from that pipe and replace every space with a hyphen.

Comments

4

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":

                                         mode command output

You can find the correct substring without looking for text:

 preg_match('/---+(\n[^|]+?){2}(?<cols>\d+)/', `mode`, $matches);
 $cols = $matches['cols'];

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:

 preg_match('/CON.*:(\n[^|]+?){3}(?<cols>\d+)/', `mode`, $matches);
 $cols = $matches['cols'];

Do test it out though, because I didn't test it.

Your method doesn't work in Win8. I get more than one --- line. i.imgur.com/4x02dqT.png
@Mark Well, great, that is just BEAUTIFUL. Thank you Windows. <3 (on a more relevant note: I'll see into how to fix that... when Windows 9 comes out :P).
This is the way I do it: $mode = `mode`; list($rows, $cols) = array_slice(preg_split('/\n/', substr($mode, strpos($mode, 'CON:'))), 2, 2);. And then I just replace everything but numbers.
@AleksandrMakov I wonder what happens if there's languages with order like CON device status:? Maybe matching something like CON.*: would work better.
@Mark I was actually questioning myself that exact thing. Why the heck did I do that? In doubt, I just assumed there was some reason and went with it, lol.
1

There 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.

function term_size
{
    local i=0 digits='' tens_fmt='' tens_args=()
    for i in {80..8}
    do
        echo $i $(( i - 2 ))
    done
    echo "If columns below wrap, LINES is first number in highest line above,"
    echo "If truncated, LINES is second number."
    for i in {1..14}
    do
        digits="${digits}1234567890"
        tens_fmt="${tens_fmt}%10d"
        tens_args=("${tens_args[@]}" $i)
    done
    printf "$tens_fmt\n" "${tens_args[@]}"
    echo "$digits"
}

This is good, if your stty won't give you real size! Very good @pourhaus ! I just changed the number in line for i in {1..14} for checking the number of columns from 14 to 25.

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.