Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I overwrite multiple lines in a shell script?

Tags:

shell

sh

echo

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?

like image 763
jrbalsano Avatar asked May 25 '13 00:05

jrbalsano


1 Answers

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.

like image 189
jrbalsano Avatar answered Sep 18 '22 06:09

jrbalsano