Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between caret notation and ANSI escape sequence

My question is raised from two different observations.

In cat, when I press ESC or other control keys, Bash uses caret notation to represent them. The figure tells I pressed ESC key, but Bash shows it as ^[.

enter image description here

Nevertheless, if I want to write colorful text in scripts, by echo for instance, it seems I have to use ANSI escape sequence.

enter image description here

The figure shows that caret notation does not work in echo, but ANSI escape sequence does.

Can I say that we must use ANSI escape sequence to enter ESC key, but Bash will use caret notation to represent it?

Is there a way to enter ESC key by caret notation? Can Bash represent an entered key in ANSI escape sequence?

Note I'm actually using ZSH. You are fine to talk about either shell.


1 Answers

If you type

$ echo 'CTRL+VESC[31mhello'

and when done it will show you

$ echo '^[[31mhello'

You probably need set -o vi in bash.

However, the best way to do that would be to use tput:

$ tput setaf 9; echo hello; tput sgr0
like image 147
Diego Torres Milano Avatar answered Mar 14 '26 08:03

Diego Torres Milano