color grep and ls on Linux

Ever wondered why grep shows the matched text/string in colour where as its not the same on other systems? or why ls on you system shows different colour for different file-types while the output on your buddy’s desktop, running some other flavour of linux, is so lifeless(without colours)? Well, thats because of the magic of dircolors and alias.

For those of you not aware of alias, its like a redirect mechanism. Here is an example for better understanding.

[shredder12]$ alias command1=”command2″

Once, this statement is executed, the next time you execute command1, it will actually result in the execution of command2.

So, the trick is to replace the regular commands like ls and grep with their activated colour options.

[shredder12]$ alias grep=”grep –color=auto”
[shredder12]$ alias ls=”ls –color=auto”

For it to be in effect across all terminals, the above two lines are included in the ~/.bashrc file

Now, you may wonder, why did I mention dircolors? What does it have to do with all this?

Well, as far as I know, dircolors is a tool to setup colours for ls. For those systems where colours on ls are pre-configured, you would notice that in the ~/.bashrc file, before aliasing they check if dircolors is installed. This is because it defines the LS_COLORS environment variable, which contains all kind of color specification for ls command, i.e. different colours for different file formats. e.g –

You can take a look at this information by entering the following command.

[shredder12]$ dircolors –print-database

Grep defaults to red colour. If you are interested in showing some other colour then it can be easily done by setting the GREP_COLOR environment variable. e.g.

[shredder12]$ export GREP_COLOR=”1;33″

This will set the colour to bright yellow. Check out the various colour attribute settings from here.

Please note that, the grep manpage clearly states that

The colors are defined by the environment variable GREP_COLORS. The deprecated environment variable GREP_COLOR is still supported, but its setting does not have priority.

But apparently, this is not the case on my system, Ubuntu 10.10. GREP_COLOR is the one that worked. I don’t know why is it so, but whatever works for you is fine.

 

source:  linuxers.org/article/how-get-text-highlighted-various-colours-grep-and-ls-linux