How to delete line with echo?

You're looking for terminal escapes. In particular, to clear from the cursor position to the beginning of the line:

echo -e "\033[1K"

Or everything on the line, regardless of cursor position:

echo -e "\033[2K"

And you can do all sorts of other neat tricks with terminal escapes too.


You can use \b or \r to move the cursor back and then overwrite the printed character with a new character. Note that neither \b nor \r deletes the printed characters. It just moves the cursor back. \b moves the cursor back one character and \r moves the cursor to the beginning of the line.

Example: both

echo -e 'foooo\b\b\b\b\bbar'

and

echo -e 'foooo\rbar'

will print:

baroo

If you want the characters deleted then you have to use the following workaround:

echo -e 'fooooo\r     \rbar'

output:

bar  

Excerpt from man echo:

   If -e is in effect, the following sequences are recognized:

   \0NNN  the character whose ASCII code is NNN (octal)

   \\     backslash

   \a     alert (BEL)

   \b     backspace

   \c     produce no further output

   \f     form feed

   \n     new line

   \r     carriage return

   \t     horizontal tab

   \v     vertical tab

   NOTE: your shell may have its own version of echo, which usually super‐
   sedes the version described here.  Please refer to your  shell's  docu‐
   mentation for details about the options it supports.

If you want to clear the line, then I suggest you use a combination of the carriage return people are mentioning and terminfo.

# terminfo clr_eol
ceol=$(tput el)
echo -ne "xyzzyxyzzy\r${ceol}foobar"

This will write xyzzyxyzzy, then return to the beginning of the line and send the "clear to end of line" sequence to the terminal, then write foobar. The -n makes echo not add a newline after the foobar.