Tuesday, March 25, 2008

Customizing the colors in ls output

This posting is specific to customizing the dircolors in bash shell in Linux. It may or may not be applicable to other shells and other platforms.

When the bash shell is started, it executes all the shell scripts under the directory /etc/profile.d/*.sh. You might find other shell scripts under this directory (for e.g. colorls.csh), but those scripts are not to be executed by the bash shell. These files are executed within the current shell's environment, not in a separate execed shell (like a dotshell).

One of these files is colorsls.sh. A set of rules in colorls.sh search for the user specific dircolors file. This file could be any one of the ~/.dircolors, ~/.dircolors.$TERM, ~/.dir_colors or ~/.dir_colors.$TERM. In case the user has more then one of these files, whichever comes last will be taken.

Let us stick to the convention of using ~/.dircolors file for our customization. It is very easy to create this file by giving the following command:
dircolors --sh > ~/.dircolors
Then you can edit ~/.dircolors using your favorite editor. This file has only one environment variable called LS_COLORS. LS_COLORS variable is ":" separated. Each entry is a name value pair. Name could be the type of the file (for e.g. di is directory, fi is regular file, ln is link, etc.) or a regular expression for file's name (for e.g. *.sh, *.csh, *.gif, etc.). Value is a ";" separated three integers that tell about the attribute, foreground and background respectively. Here is an example (the color rule for a directory):
di=00;34:
This says the directory should be displayed with no special attributes and blue foreground. You can easily check the color codes using the following command:
dircolors --print-database
For handy reference, this is what I see in my machine:
# Attribute codes:
# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
# Text color codes:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
# Background color codes:
# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
So let us say I want to make my directories to be yellow and blinking, this is how I would have that entry:
di=05;33:
You must remember that not all attributes are supported by all the terminals. Some terminals have limited capabilities.

A tip: In case you are totally fed up with colors (just the way I am), a sane alternative is to use the following alias (like they might not be able to show blinking text).
alias ls='ls --color=none -F'
This will add a "/" after directory, "*" after executable and "@" after a link, etc.

No comments: