Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash - color escapes codes

I have a script that uses escape codes to highlight text matches in its output. All is good except when the output is piped to less, which prints the escape codes

e.g.

$ echo -e "\033[31m -- Hello World! -- \033[m"
 -- Hello World! --

Piped to less:

$ echo -e "\033[31m -- Hello World! -- \033[m" | less
ESC[31m -- Hello World! -- ESC[m

I was wondering how other tools like ls, grep, etc are able to output in color yet it looks fine when piped to less?

like image 710
armandino Avatar asked Nov 22 '11 00:11

armandino


2 Answers

Use less -R or add LESS=-R to the environment. This requests that less pass some escape sequences (such as color) to the terminal instead of printing them as normal characters.

like image 107
ephemient Avatar answered Sep 21 '22 20:09

ephemient


grep and friends detect whether output is to a terminal. When piped to less, it isn't, so they disable colouring.

Look at isatty to check whether the output is a terminal.

Note that I sometimes find this quite annoying because I want less to display the colors:

alias less='less -SR'
alias grep='grep --color=always'

Also look at ANSIFilter for the reverse: to filter ANSI escapes out of existing streams (you can also use it to produce HTML, RTF, and possibly other formats from them)

like image 34
sehe Avatar answered Sep 23 '22 20:09

sehe