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

fd3cxomn  于 2023-08-07  发布在  Shell
关注(0)|答案(4)|浏览(98)

我建立了我的网络服务器,我想做一个测试。所以我用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
因此,我为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

bfrts1fy

bfrts1fy1#

还有另一个选项,在写入stdout之前定位光标。
您可以根据需要设置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

字符串

hiz5n14c

hiz5n14c2#

您可以在while循环的开头添加clear命令。这将使echo语句在每次迭代期间保持在屏幕顶部,如果这就是您所想的。

ryoqjall

ryoqjall3#

当我做这类事情时,我不使用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

字符串
如果您没有显示可预测长度的文本,则可能需要首先重置显示(因为它不会清除内容,所以如果您从there转到here,则最终将显示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(这会关心顺序!).

0mkxixxg

0mkxixxg4#

请在下面尝试。

#!/bin/bash

echo -e "\033[s" 

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

字符串

相关问题