Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

text - Backspace character weirdness

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 "abcxyz"
xyz

( 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 "abcx"
xbc

it behaves like left arrow keys instead of backspace:

$ echo -e "abce[De[De[Dx"
xbc

erase line back works normally:

$ echo -e "abce[1Kx"
x

In fact, when I type Ctrl+V Backspace 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 is xterm Linux and some other terminal emulators, $TERM == xterm, tried vt100, Linux as well)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...