如何删除和使用bash替换最后一行在终端?如何删除和使用bash替换最后一行在终端?(How to

2019-05-13 03:45发布

我想实现显示在bash经过秒的进度条。 对于这一点,我需要清除屏幕上显示的最后一行(命令“清除”删除所有画面,但我只需要删除的进度条的线,并与新的信息替换它)。

最终的结果应该是这样的:

$ Elapsed time 5 seconds

然后10秒后我要替换这句话(在屏幕同一位置):

$ Elapsed time 15 seconds

Answer 1:

回声与\ r回车

seq 1 1000000 | while read i; do echo -en "\r$i"; done

从人的回声:

-n     do not output the trailing newline
-e     enable interpretation of backslash escapes

\r     carriage return


Answer 2:

通过自身的回车只是将光标移动到该行的开头。 这是确定的,如果输出的每个新行至少只要前面的一个,但如果新的线路较短,前行不会完全覆盖,例如:

$ echo -e "abcdefghijklmnopqrstuvwxyz\r0123456789"
0123456789klmnopqrstuvwxyz

要真正清除新的文本行,你可以添加\033[K\r

$ echo -e "abcdefghijklmnopqrstuvwxyz\r\033[K0123456789"
0123456789

http://en.wikipedia.org/wiki/ANSI_escape_code



Answer 3:

德里克维特的答案,只要行的长度不会超过终端宽度效果很好。 如果不是这种情况,下面的代码将防止垃圾输出:

之前该行已为第一次写,做

tput sc

这节省了当前光标位置。 现在,只要你想打印线,使用

tput rc
tput ed
echo "your stuff here"

先返回到保存的光标位置,然后从游标清除屏幕上下,终于写出输出。



Answer 4:

该\ 033的方法并没有为我工作。 该\ r方法的工作原理,但它实际上并没有删除任何东西,只是把光标在该行的开头。 因此,如果新的字符串比旧的更短,你可以看到在该行的最后剩余的文本。 到底是tput的去的最佳途径。 它有其他用途,除了光标的东西,再加上它预装在许多Linux和BSD发行版,所以应该是适用于大多数bash用户。

#/bin/bash
tput sc # save cursor
printf "Something that I made up for this string"
sleep 1
tput rc;tput el # rc = restore cursor, el = erase to end of line
printf "Another message for testing"
sleep 1
tput rc;tput el
printf "Yet another one"
sleep 1
tput rc;tput el

这里有一个小的倒计时脚本一起玩:

#!/bin/bash
timeout () {
    tput sc
    time=$1; while [ $time -ge 0 ]; do
        tput rc; tput el
        printf "$2" $time
        ((time--))
        sleep 1
    done
    tput rc; tput ed;
}

timeout 10 "Self-destructing in %s"


Answer 5:

使用回车符:

echo -e "Foo\rBar" # Will print "Bar"


Answer 6:

如果进展输出为多行或脚本将已打印的新行字符,你可以跳线与类似:

printf "\033[5A"

这将使光标跳到5行了。 然后你就可以覆盖任何你所需要的。

如果不工作,你可以尝试printf "\e[5A"echo -e "\033[5A" ,它应该有同样的效果。

基本上, 转义序列可以控制屏幕几乎一切。



Answer 7:

可以通过放置回车实现它\r

在的代码与单个线printf

for i in {10..1}; do printf "Counting down: $i\r" && sleep 1; done

echo -ne

for i in {10..1}; do echo -ne "Counting down: $i\r" && sleep 1; done


Answer 8:

最简单的方法是使用\r字符我猜。

其缺点是,你不能拥有完整的生产线,因为它仅清除当前行。

简单的例子:

time=5
echo -n "Elapsed $time seconds"
sleep 10
time=15
echo -n "Elapsed $time seconds"

echo "\nDone"


文章来源: How to delete and replace last line in the terminal using bash?