Shell – Difference Between \e and ^[ Escape Characters

escape-characterskey mappingshell

Gilles wrote:

character 27 = 033 = 0x1b = ^[ = \e

Demizey wrote:

^[ is just a representation of ESCAPE and \e is interpreted as an actual ESCAPE character

Then I also found this line from a TechRepublic article

Make sure you write the key sequence as \e[24~ rather than ^[[24~. This is because the ^[ sequence is equivalent to the [Esc] key, which is represented by \e in the shell. So, for instance, if the key sequence was ^[[OP the resulting bind code to use would be \e[OP.

But I have been using mappings that use ^[ instead of \e.

So are they interchangeable? When do I need use one instead of the other?

Best Answer

If you take a look at the ANSI ASCII standard, the lower part of the character set (the first 32) are reserved "control characters" (sometimes referred to as "escape sequences"). These are things like the NUL character, Life Feed, Carriage Return, Tab, Bell, etc. The vast majority can be emulated by pressing the Ctrl key in combination with another key.

The 27th (decimal) or \033 octal sequence, or 0x1b hex sequence is the Escape sequence. They are all representations of the same control sequence. Different shells, languages and tools refer to this sequence in different ways. Its Ctrl sequence is Ctrl-[, hence sometimes being represented as ^[, ^ being a short hand for Ctrl.

You can enter control character sequences as a raw sequences on your command line by proceeding them with Ctrl-v. Ctrl-v to most shells and programs stops the interpretation of the following key sequence and instead inserts in its raw form. If you do this with either the Escape key or Ctrl-v it will display on most shells as ^[. However although this sequence will get interpreted, it will not cut and paste easily, and may get reduced to a non control character sequence when encountered by certain protocols or programs.

To get around this to make it easier to use, certain utilities represent the "raw" sequence either with \033 (by octal reference), hex reference \x1b or by special character reference \e . This is much the same in the way that \t is interpreted as a Tab - which by the way can also be input via Ctrl-i, or \n as newline or the Enter key, which can also be input via Ctrl-m.

So when Gilles says:

27 = 033 = 0x1b = ^[ = \e

He is saying decimal ASCII 27, octal 33, hex 1b, Ctrl-[ and \e are all equal he means they all refer to the same thing (semantically).

When Demizey says

^[ is just a representation of ESCAPE and \e is interpreted as an actual ESCAPE character

He means semantically, but if you press Ctrl-v Ctrl-[ this is exactly the same as \e, the raw inserted sequence will most likely be treated the same way, but this is not always guaranteed, and so it recommended to use the programmatically more portable \e or 0x1b or \033 depending on the language/shell/utility being used.