How do I overwrite multiple lines in a shell script?

旧街凉风 提交于 2020-01-01 00:39:08

问题


I want to write multiple lines over and over to the terminal. Something like

echo "One Line"
echo "Two Lines"
echo "\r\b\rThree Lines"
echo "Four Lines"

Ideally this would first output:

One Line
Two Lines

And this output would then be replaced with

Three Lines
Four Lines

Trouble is, while the carriage return will let you overwrite one line of output, you can't get past the \n with a \b. How do I then overwrite multiple lines?


回答1:


I found a solution for this one that took a little digging and I'm still not entirely sure on how this one works. However, it seems the program tput will allow you to get special characters for clearing lines and position the cursor. Specifically, tput el will clear to the beginning of the current line (instead of just repositioning the cursor). Conveniently, tput cuu1 will move the cursor up one line. So if in your bash script you declare variables like:

UPLINE=$(tput cuu1)
ERASELINE=$(tput el)

You could then write a script like so:

UPLINE=$(tput cuu1)
ERASELINE=$(tput el)
echo "One Line"
echo "Two Lines"
echo "$UPLINE$ERASELINE$UPLINE$ERASELINE\c"
echo "Three Lines"
echo "Four Lines"

and you'll get the desired output.



来源:https://stackoverflow.com/questions/16745407/how-do-i-overwrite-multiple-lines-in-a-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!