如何在相同位置回显字符串?

4
我搭建了我的网页服务器,现在正在进行测试。所以我用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都放在同一个位置。
我已经阅读了这篇文章:如何在同一行显示和更新echo

所以我给echo添加了-ne,但它似乎并没有按预期工作。
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

我不知道是否有更简单的方法来解决这个问题,但是使用ncurses库可以实现你想要的功能。 - sid-m
@sid-m 好的,谢谢。 - Yves
4个回答

6

还有一种选择,就是在向标准输出写入内容之前定位光标。

您可以根据需要设置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

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

0
你可以在 while 循环的开头添加一个 clear 命令。这样,在每次迭代期间,echo 语句就会保持在屏幕顶部,如果这是你想要的效果的话。

也许你可以将curl管道传输到head/tail -n 30,以控制输出的行数,并防止打印足够多的内容将标题推出屏幕? - Adam Schettenhelm

0

当我做这种事情时,我不使用curses / 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(这将关心顺序!),那么这将更加简洁。


0

请尝试以下...

#!/bin/bash

echo -e "\033[s" 

echo -e "\033[u**Your String Here**"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接