作为一个简单的例子,我想写一个CLI脚本,它可以在终端窗口的整个宽度上打印=。

#!/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表示列数。 Tput行数告诉你行数。

其他回答

正如我在lyceus的回答中提到的,他的代码在非英语区域设置的窗口上将失败,因为mode的输出可能不包含子字符串“columns”或“lines”:

                                         

你可以找到正确的子字符串而不寻找文本:

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

请注意,我甚至没有费心于线条,因为它不可靠(实际上我并不关心它们)。

编辑:根据对Windows 8的评论(哦,你…),我认为这可能更可靠:

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

不过一定要测试一下,因为我没有测试过。

在POSIX上,最终需要调用TIOCGWINSZ(获取窗口大小)ioctl()调用。大多数语言都应该为此提供某种包装器。例如,在Perl中,你可以使用Term::Size:

use Term::Size qw( chars );

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

受到@pixelbeat的回答的启发,这里有一个由tput带来的水平条,稍微滥用printf填充/填充和tr

printf "%0$(tput cols)d" 0|tr '0' '='
yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'

要在Windows CLI环境中做到这一点,我能找到的最佳方法是使用mode命令并解析输出。

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;
}

希望对大家有用!

注意:返回的高度是缓冲区中的行数,而不是窗口中可见的行数。还有更好的选择吗?