How to delete and replace last line in the terminal using bash? How to delete and replace last line in the terminal using bash? bash bash

How to delete and replace last line in the terminal using bash?


The carriage return by itself only moves the cursor to the beginning of the line. That's OK if each new line of output is at least as long as the previous one, but if the new line is shorter, the previous line will not be completely overwritten, e.g.:

$ echo -e "abcdefghijklmnopqrstuvwxyz\r0123456789"0123456789klmnopqrstuvwxyz

To actually clear the line for the new text, you can add \033[K after the \r:

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

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


echo a carriage return with \r

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

from man echo:

-n     do not output the trailing newline-e     enable interpretation of backslash escapes\r     carriage return


Derek Veit's answer works well as long as the line length never exceeds the terminal width. If this is not the case, the following code will prevent junk output:

before the line is written for the first time, do

tput sc

which saves the current cursor position. Now whenever you want to print your line, use

tput rctput edecho "your stuff here"

to first return to the saved cursor position, then clear the screen from cursor to bottom, and finally write the output.