2017-06-21 12 views
0

我构建了我的web服务器,并且正在尝试做一个测试。所以,我与模拟bash脚本许多要求:
bash:如何在同一位置回显字符串

i=0 
while [ $i -lt 20 ]; do 
    echo '' 
    echo '' 
    echo '' 
    echo '============== current time ===============' 
    echo $i 
    echo '===========================================' 
    echo '' 
    curl -i http://www.example.com/index?key=abceefgefwe 
    i=$((i+1)) 
done 

这种运作良好,但我更愿意让所有的echo在终端上的同一位置。
我读过这样的:How to show and update echo on same line

所以我添加-neecho,但它似乎并不如预期的工作。
curl的消息仍然可以将echo推开。

这就是我需要:

============== current time =============== ---\ 
1 <------ this number keeps updating  ----> the 3 lines stay here 
=========================================== ---/ 
Here is the messages of `curl`, which are showing as normal way 
+0

我不知道是否有更简单的方法来解决这个问题,但'ncurses'库你可以实现你想要的。 –

+0

@ sid-m好的,谢谢。 – Yves

回答

2

还有另一种选择,在写入标准输出之前定位光标。

您可以设置xy以满足您的需求。

#!/bin/bash 

y=10 
x=0 
i=0 
while [ $i -lt 20 ]; do 
    tput cup $y $x 
    echo '' 
    echo '' 
    echo '' 
    echo '============== current time ===============' 
    echo $i 
    echo '===========================================' 
    echo '' 
    curl -i http://www.example.com/index?key=abceefgefwe 
    i=$((i+1)) 
done 
+0

非常感谢!这正是我需要的。 – Yves

1

你可以在你的while循环的开头添加一个clear命令。如果这是你的想法,这将在每次迭代期间将回显语句保留在屏幕的顶部。

+0

我不想使用'clear'。这不够好。 – Yves

+0

嗯...也许我没有别的选择... – Yves

+0

也许你可以用卷曲来控制头部/尾部-n 30来控制输出的行数并防止打印足以将头部从屏幕上移开? –

0

当我做这样的事情,而不是使用诅咒/ ncurses的或tput,我只是把自己限制在一个单一的线,并希望它不换行。我每次迭代都会重新绘制线条。

例如:

i=0 
while [ $i -lt 20 ]; do 
    curl -i -o "index$i" 'http://www.example.com/index?key=abceefgefwe' 
    printf "\r==== current time: %2d ====" $i 
    i=$((i+1)) 
done 

如果你没有显示预测的长度的文本,则可能需要先重新设置显示器(因为它没有明确的内容,因此,如果您从therehere,您将以heree结尾,并带有前一个字符串的额外字母)。为了解决这个:

i=$((COLUMNS-1)) 
space="" 
while [ $i -gt 0 ]; do 
    space="$space " 
    i=$((i-1)) 
done 
while [ $i -lt 20 ]; do 
    curl -i -o "index$i" 'http://www.example.com/index?key=abceefgefwe' 
    output="$(head -c$((COLUMNS-28))) "index$i" |head -n1)" 
    printf "\r%s\r==== current time: %2d (%s) ====" "$space" $i "$output" 
    i=$((i+1)) 
done 

这使得全宽线的空间,以清除以前的文本,然后写了新的内容,现在空行。我已经使用了检索文件的第一行的一段,直到最大行宽(计算额外的文本;我可能在某处关闭)。如果我可以使用head -c$((COLUMNS-28)) -n1(这将关心订单!),这将更清洁。

相关问题