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
?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With