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

Debugger picture Debugger · Mar 5, 2010 · Viewed 80.5k times · Source

I want to implement a progress bar showing elapsed seconds in bash. For this, I need to erase the last line shown on the screen (command "clear" erases all the screen, but I need to erase only the line of the progress bar and replace it with the new information).

Final result should look like:

$ Elapsed time 5 seconds

Then after 10 seconds i want to replace this sentence (in the same position in the screen) by:

$ Elapsed time 15 seconds

Answer

Derek Veit picture Derek Veit · Jul 21, 2011

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