How do I find the width & height of a terminal win

2020-02-02 03:48发布

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

标签: terminal
9条回答
地球回转人心会变
2楼-- · 2020-02-02 04:28

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?

查看更多
\"骚年 ilove
3楼-- · 2020-02-02 04:36
  • tput cols tells you the number of columns.
  • tput lines tells you the number of rows.
查看更多
We Are One
4楼-- · 2020-02-02 04:37
yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'
查看更多
登录 后发表回答