17

Apologies if this has already been asked, but I have no idea how I can find this out myself - when I search for "^[[A" in any search engine it ignores the "^[[" part altogether.

Anyway, my question: Sometimes in terminal (on a Mac) when I hit the arrow keys, the characters "^[[A", "^[[B", "^[[C" or "^[[D" appear. I seem to remember encountering this years ago when using (most likely) DOS as well and I think it occured a lot more frequently too.

Why does this happen and what do they mean?

1
  • when search engines ignore such characters, you can spell them out like in the question title, ie 'caret square bracket ...'
    – tyrex
    Sep 30 '20 at 13:04
23

These are ANSI escape codes. The ^[ represents an ESC (escape) character, the next [ is an actual left square bracket, and the letter indicates the function of the escape code. The Esc[ part is called the CSI (Control Sequence Introducer). So the sequence CSI A means arrow up, or CUU (CUrsor Up).

Anyway, this scheme dates back to the time of the VT100 display terminal (introduced in 1978). Some of the escape sequences used by the VT100 were standardized by ANSI in the early 1980s and have remained in common use since then.

Normally, when you hit the arrow keys, some program (say the shell) is listening and can act upon them. So when you hit the up arrow, it scrolls back in your command history. However, if a program is running that doesn't understand the escape sequences for arrow keys, then they usually end up getting echoed back to the terminal just like any other key you might hit. So that is why you sometimes see ^[[A if you hit the up arrow key.

3
  • It's worth also pointing out that ^ is the common UNIX convention to show "control" in the terminal. For example, if you were to press Ctrl+A and it were to be ignored in the same way it would be shown as "^A". Ctrl+[ is actually a synonym for the escape character. Incidentally, what is it that makes this happen in the first place; which software decides to print the caret? Is it the terminal emulator itself, or something else I'm not aware of?
    – Muzer
    Aug 13 '15 at 12:45
  • @Muzer the kernel itself does caret-formatting of echoed characters. The feature can be turned off with stty -echoctl
    – user41515
    Aug 13 '15 at 14:45
  • The kernel? Interesting, I didn't know it went that deep (though in hindsight, it should have been obvious, since it even happens at very early stages of bootup!).
    – Muzer
    Aug 13 '15 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.