作为一个简单的例子,我想写一个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
当前回答
在某些情况下,您的行/行和列与所使用的“终端”的实际大小不匹配。也许你没有“tput”或“stty”可用。
下面是一个bash函数,您可以使用它来直观地检查大小。这将工作到140列x 80行。您可以根据需要调整最大值。
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"
}
其他回答
在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' '='
要在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;
}
希望对大家有用!
注意:返回的高度是缓冲区中的行数,而不是窗口中可见的行数。还有更好的选择吗?
在某些情况下,您的行/行和列与所使用的“终端”的实际大小不匹配。也许你没有“tput”或“stty”可用。
下面是一个bash函数,您可以使用它来直观地检查大小。这将工作到140列x 80行。您可以根据需要调整最大值。
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"
}
在bash中,$LINES和$COLUMNS环境变量应该能够做到这一点。将在终端大小发生任何变化时自动设置。(即SIGWINCH信号)