使用 echo 更新终端中的多行

Update multiple line in terminal with echo

我有一个项目要完成,但我有点误解了这个主题。

Objectiv

作为测试,我尝试了从命令 ps 模拟的 10 行,持续 30 秒。 `

#!/bin/bash
test=$(ps -ao pid,pcpu,time,comm | head -n10)

for time in $(seq 1 30); do
    echo -ne "$test\r"
    sleep 1
    test=$(ps -ao pid,pcpu,time,comm | head -n10)
done

注意:该示例不是我的作业,但它代表了我现在面临的挑战

感谢您的宝贵时间。

最简单、最便携和最稳定的解决方案是在每次迭代时清除屏幕:

#!/bin/bash

for i in {1..30} ; do
    clear

    # Print several lines
    printf "foo %d\n" "${i}"
    printf "bar %d\n" "${i}"

    sleep 1
done

或者您可以使用以下序列:

# Save the cursor position
printf "3[s"
# Print two empty dummy lines
printf "\n\n"

for i in {1..30} ; do
    # Delete the last two lines
    printf "3[2K"
    # Restore the cursor position
    printf "3[u"

    # Print two lines
    printf "foo ${i}\n"
    printf "bar ${i}\n"

    sleep 1
done

请注意,上述 ^^^ 解决方案只有在您事先知道要打印/清除的行数时才有效。

可以用echo -e "\e[nA"排n行(n应该是整数)。如果所有行的长度相同,则执行以下操作。

lines=10
for i in {0..30}; do
    ps -ao pid,pcpu,time,comm | head -n${lines}  # print `$lines` lines
    sleep 1
    echo -e "\e[$((${lines}+1))A"                # go `$lines + 1` up
done