Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have this:

I read down arrow key

abc@abc-ubuntu:~/bashpratice$ read -n 3 key
^[[Babc@abc-ubuntu:~/bashpratice$ 

I am able to grep for it

abc@abc-ubuntu:~/bashpratice$ echo $key | grep '\['
[B
abc@abc-ubuntu:~/bashpratice$ echo $key | grep '\[B'
[B

But echoing the key just prints spaces

abc@abc-ubuntu:~/bashpratice$ echo $key

abc@abc-ubuntu:~/bashpratice$ 

Why does echoing the key just give spaces?

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

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.

share|improve this answer
    
To obtain expected results, it might be a good thing to reset a terminal before experimenting with escape sequences. –  Stéphane Gimenez Aug 24 '11 at 17:51
    
Thanks for the wonderful explanation. –  abc Aug 25 '11 at 15:23
add comment

The terminal does not respond to key codes. Those are normally seen and interpreted by the application. They application may send a cup (cursor up), or down sequence (usually using the ncurses library).

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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