作为一个简单的例子,我想写一个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
作为一个简单的例子,我想写一个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
当前回答
要在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信号)
受到@pixelbeat的回答的启发,这里有一个由tput带来的水平条,稍微滥用printf填充/填充和tr
printf "%0$(tput cols)d" 0|tr '0' '='
还有stty,请参阅stty:打印或更改终端特征,更具体地说是特殊设置
$ 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
它将分别打印行数和列数,或者高度和宽度。
或者,您可以使用cut或awk来提取所需的部分。
stty大小为| cut -d" " -f1表示高度/行,stty大小为| cut -d" " -f2表示宽度/列
要在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;
}
希望对大家有用!
注意:返回的高度是缓冲区中的行数,而不是窗口中可见的行数。还有更好的选择吗?
yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'