colouring output of ls according to file extension

I am working on some C++ files all of which are in a single folder.

When I do ls both the .cpp and the .h files show up in the same colour.

Is there a way to tell the bash shell that I want to display .cpp files in pink and .h files in golden-brown?


Solution 1:

If you're working with GNU coreutils (very likely if you're on Linux), you're looking for the dir_colors utility.

If your distribution has already set everything up so that you get different colors in ls for some file types, you just need to, for example, copy /etc/DIR_COLORS to your ~/.dir_colors, make the changes you want, then start a new shell to see the effects.

If not, still copy the file over to your home directory as above. Then you'll need to:

  • put this somewhere in your shell's rc files:

    eval `dircolors ~/.dir_colors`
    
  • alias ls to ls --color=auto (put that in your rc files as well)

You can get this on Mac OS X too via coreutils MacPort. A better ls for Mac OS X has some details on this (pay attention to the with_default_names option, make sure you understand the implications of using it if/before you do).

For FreeBSD (don't know if this applies to other BSD variants), the option for ls would be -G, and check out the ls(1) man page description for the CLICOLORS environment variable for a bit more info.