退格字符怪异
我想知道为什么常见 Linux 终端中的退格字符在打印时实际上不会删除字符(通常在键入时起作用)。
这按预期工作:(
$ echo -e "abc\b\b\bxyz"
xyz
\b
计算为退格键,也可以插入作为 Ctrl+V Ctrl+H - 呈现为 ^H
(0x08
))
但是当退格键后的字符较少时,奇怪的行为就会显现出来:
$ echo -e "abc\b\b\bx"
xbc
它的行为就像向左箭头键而不是退格键:
$ echo -e "abc\e[D\e[D\e[Dx"
xbc
擦除行后退正常工作:
$ echo -e "abc\e[1Kx"
x
事实上,当我输入 Ctrl 时+V Backspace 在终端中,生成 ^?
(0x7f
) 而不是 ^H
,这是 Del ascii 字符,但 Ctrl+V Del 产生
,但这是另一个故事..
那么有人可以解释为什么打印的退格字符不会删除字符吗?
(我的环境是xterm Linux和其他一些终端模拟器,$TERM
== xterm
,尝试了vt100
,Linux
以及)
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
it 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 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你所看到的是正确的。退格键或
^H
将光标向左移动,不擦除。要删除一个字符,需要输出^H ^H
(退格-空格-退格)。回答你的评论 - 退格键在 VT100/ANSI 系列终端中是这样定义的,从中借用了很多终端控制代码序列。请参阅此处的VT100用户手册,其中将BS的功能定义为“将光标向左移动”一个字符位置,除非它位于左边距,在这种情况下不会发生任何操作”。换句话说,这是历史的一个怪癖:)
至于为什么它最初是这样定义的 - 我想拥有非破坏性的光标移动控制代码会更灵活,因为可以如上所示实现破坏性的退格键。
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.