作为一个简单的例子,我想写一个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行数告诉你行数。

其他回答

yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'

Tput cols表示列数。 Tput行数告诉你行数。

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

希望对大家有用!

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

在bash中,$LINES和$COLUMNS环境变量应该能够做到这一点。将在终端大小发生任何变化时自动设置。(即SIGWINCH信号)

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

use Term::Size qw( chars );

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