What happens when downarrow is typed in a terminal
As reported by xxd -p, when typing ↓ + return :
xxd -p
^[[B
1b5b420a
The downarrow key leads to a sequence of 3 characters:
- the first is
\x1b (a.k.a. escape, see man ascii), echoed on the terminal as ^[,
- second is
\x5b, that is [,
- third is
\x42, that is B.
The last character, \x0a is just the newline character.
So, downarrow is echoed on the terminal as ^[[B. In reality, this corresponds to the 1b5b42 hex sequence, which is the one actually sent to the reading process.
About your experiments
Your key variable contains the 1b5b42 hex sequence. Check it with
echo -n "$key" | xxd -p
1b5b42
Of course, grep will be able to catch the 5b42 hex sequence (that is [B)¹.
However, when you send something to the terminal, the escape character \x1b is interpreted as the beginning of some special escape sequence. For example \x1b[31m is a sequence that is recognized by most terminals and means "use red foreground color". Check it yourself:
echo -e 'hello \x1b[31myou'
The sequence will change the current color, but it will not print anything.
You can also check this:
echo -e 'hello \x1b[Byou'
and you'll see that the special sequence \x1b[B is interpreted by the terminal as "move the cursor down by one".
That's why your echo $key won't show something directly visible on the terminal, except for some blank lines.
—
1. I'm not sure why grep happens to print just [B, I have some different result on my setup.