34

Is it possible to echo a backspace in bash?

Something like

echo $'stack\b'

Shouldn't output stac? Or I'm missing something?

More specifically, I'd like to use that in:

ls | wc -l; echo $'\b items'
sidyll
  • 57,726
  • 14
  • 108
  • 151

3 Answers3

50

\b makes the cursor move left, but it does not erase the character. Output a space if you want to erase it.

For some distributions you may also need to use -e switch of echo:

  -e     enable interpretation of backslash escapes

So it will look like

 echo -e 'stack\b '

Also, files=(*) ; echo "${#files[@]} items".

Ry-
  • 218,210
  • 55
  • 464
  • 476
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Hmm, and of course it's not possible to backspace on a new line, right? That's why my initial solution didn't work (I guess). Thanks for the nice solution to the files count. I'd give +2 if I could :-) – sidyll Apr 19 '11 at 23:37
  • Why doesn't this method of deletion doesn't work for newlines? – Geremia Aug 04 '17 at 21:24
  • `\b` goes back a single character, up to the left edge of the terminal. A newline is literally a *new line*, so the second line has its own left edge. – Ignacio Vazquez-Abrams Aug 04 '17 at 21:28
9

So to answer the actual question about backspaces this will simulate a backspace:

echo -e "\b \b"

It will move the character back one, then echo a space overwriting whatever character was there, then moving back again - in effect deleting the previous character. It won't go back up a line though so the output before that should not create a new line:

echo -n "blahh"; echo -e "\b \b"
rawbone
  • 91
  • 1
  • 2
1

It is not exactly what you're asking for, but also, in the line of Ignacio's answer, you could use for this case:

echo "$(ls | wc -l) items"

AFAIK you cannot print a character that deletes the one before, not even printing the char whose hexadecimanl number correspoonds to backspace. You can move back and print a blank space to delete, though. With cput you can do many things and print wherever you want in the screen.

Robert Vila
  • 221
  • 3
  • 2