views:

90

answers:

1

i wonder why backspace character in common linux terminals does not actually erase the characters, when printed (which normally works when typed)..

this works as expected:

$ echo -e "abc\b\b\bxyz"
xyz

(\b evaluates to backspace, can be inserted also as ctrl-v ctrl-h - rendered as ^H (0x08))

but when there are less characters after the backspaces, the strange behavior is revealed:

$ echo -e "abc\b\b\bx"
xbc

is behaves like left arrow keys instead of backspace:

$ echo -e "abc\e[D\e[D\e[Dx"
xbc

erase line back works normally:

$ echo -e "abc\e[1Kx"
x

in fact, when i type ctrl-v <BS> in terminal, ^? (0x7f) is yielded instead of ^H, this is DEL ascii character, but ctrl-v <DEL> produces <ESC>[3~, but it is another story..

so can someone explain why printed backspace character does not erase the characters?

(my environment it xterm linux and some other terminal emulators, $TERM == xterm, tried vt100, linux as well)

+3  A: 

What you are seeing is correct. Backspace or ^H moves the cursor to the left, no erasing. To erase a character, you need to output ^H ^H (Backspace-Space-Backspace).


To answer your comment - Backspace is defined that way in the VT100/ANSI family of terminals, from which a lot of terminal control code sequences borrow. See the VT100 user manual here which defines the function of BS as "Moves cursor to the left one character position, unless it is at the left margin, in which case no action occurs". In other words it's a quirk of history :)

As to why it was defined this way initially - I guess it's more flexible to have a non destructive cursor movement control code, as destructive backspace can be implemented as shown above.

spong
well, this is not an explanation _why_ backspace control character behaves like left cursor key, not according to commons sense (erase last character)
mykhal
now i'm satisfied, thanks for the spec link :)
mykhal