有没有办法在不清除屏幕的情况下更换线路


printf "line onen"
printf "line twon"

在这些打印输出之后,我想替换第一行并打印其他内容(不使用clear(。我尝试过以下命令:

printf "line onen"
printf "line twor"

这不是我想要的,因为它取代了最后一行line two,而不是line one

我想做的事:

printf "line onen"
printf "line twon"
sleep 0.5
somecode "line three"

我想要的输出:

line three
line two

这可以用tput来完成,例如:

EraseToEOL=$(tput el)                 # save control code for 'erase to end of line'
tput sc                               # save pointer to current terminal line
printf "line one - a long linen"
printf "line twon"
sleep 0.5
tput rc                               # return cursor to last cursor savepoint (`tput sc`)
printf "line three${EraseToEOL}n"    # print over `line one - a long line`; print `$EraseToEOL` to clear rest of line (in case previous line was longer than `line three`)
printf "n"                           # skip over 'line two'

这将首先打印:

line one - a long line                # `tput sc` will point to this line
line two
<cursor>                              # cursor is left sitting on this line

然后在睡眠0.5秒后,tput rc将导致光标向上移动2行,然后执行最后2个printf命令:

line three                            # old 'line one - a long line` is overwritten
line two                              # `printf "n"` won't print anything new on this line so the old contents won't be overwritten, while the cursor will be moved to the next line
<cursor>                              # cursor is left sitting on this line

另一个例子:这里是

一些文档:此处和此处

您可以通过打印特殊的转义序列在bash脚本中移动光标,请尝试以下代码:

#!/bin/bash
# print first line
printf "first line is longn"
# print second line
printf "line 2n"
sleep 1
# move cursor two steps UP
printf "33[2A"
# print line 3 (without n)
printf "line #3"
# clear rest of first line
# and move cursor two steps down
printf "33[Kr33[2B"

有关ANSI转义序列的详细信息:https://tldp.org/HOWTO/Bash-Prompt-HOWTO/c327.html

相关内容

最新更新