作为一个简单的例子,我想写一个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"
}

其他回答

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

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'];

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

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

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

printf "%0$(tput cols)d" 0|tr '0' '='