OS X Terminal – How to Change Output Color of ls Command in iTerm2

bsdcolorslsosx

I know that a similar question has been asked in:

How to colorize output of ls ?

although I didn't really understand the answer and couldn't really make it work.

However, I have tried something different. I decided to read the manual page for ls and it mentions different environment variables that can be set when dealing with the ls command. If one goes to the -G option it says to look at the CLICOLOR environment variables. I did and that one links you to documentation for the LSCOLORS environment variable. I went to it and it mentions:

"The value of this variable describes what color to use for which attribute when colors are enabled with CLICOLOR. This string is a concatenation of pairs of the format fb, where f is the foreground color and b is the background color. "

It also mentions that the default value of LSCOLORS is "exfxcxdxbxegedabagacad" and that each part specifies the color of some specific thing in the ls command. For example, the first pair ex in example specifies the color of directories. the second fx the color of symbolic links etc… e means blue and x means default "foreground".

1) First what does this mean: "when colors are enabled with CLICOLOR"?

2) What does "foreground" mean?

What must environment variables be for the ls command to color the output however I desire?


I also tried:

ls --color

But it threw me the following error:

ls: illegal option -- - usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]

The same error happened when I did ls --color=auto: it alone also throws an error. I have no idea why, and am not sure if it was due to iTerm2 or OS X or why that happened. It seems it works on other systems…

Best Answer

While trying to answer my own question I tried some different things and it all worked out by experimenting.

1) I am guessing that "enabling CLICOLOR" means to set it to 1 (i.e. true) because once I set that variable to 1, the LSCOLOR started to work.

2) In this context, "Foreground" means the background highlighting that it will apply. For example, bc for the first pair, means it will color the chars for directories in red while the background/highlighting for it will be green. For example if your environment var is as: export LSCOLORS="bCfxcxdxbxegedabagacad"

then doing ls shows something like this:

enter image description here

Obviously, for this to work the ls command has to be aliased to ls -G (or just do ls -G everytime) and you have to have the following lines in your .bashrc or whatever shell rc file you use:

export CLICOLOR=1
export LSCOLORS="gxfxcxdxbxegedabagacad"

Now you can change the LSCOLORS however you want as specified by the man ls file.

There might be different ways of making this work, but this is how it worked for me on Unix in OS X mavericks on iTerm2.

Related Question