Search code examples
bashreplaceterminalline

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


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

Solution

  • 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