1

So I know that there is a way to change the color of text for directories, regular files, bash scripts, etc. Is there a way to change the color to the file based on the _file extension_?

Example:

$ ls -l foo.txt [is red] foo.text [is blue] foo.secret [is green] foo.txt [is red] 
0

2 Answers 2

7

Yes, using the LS_COLORS variable (assuming GNU ls). The easiest way to manipulate that is to use dircolors:

dircolors --print-database > dircolors.txt 

will dump the current settings to dircolors.txt, which you can then edit; once you've added your settings,

eval $(dircolors dircolors.txt) 

will update LS_COLORS and export it. You should add that to your shell startup script.

To apply the example settings you give, the entries to add to dircolors.txt would be

.txt 00;31 .text 00;34 .secret 00;32 
3
  • Thanks man. btw, could this work? .tar.gz 01;31 and .zip.gz 02;31 work? Commented Nov 10, 2016 at 6:48
  • It's easy enough to try for yourself ;-). But yes, it will work, although 02 doesn't match anything so 02;31 is equivalent to 00;31 (standard red). Commented Nov 10, 2016 at 8:05
  • in many terminal emulators, 02 is used to dim the color Commented Oct 15, 2020 at 13:51
0

One way to do this (not the best way) is to make a custom shell function:

myls() { for f in *; do if [ "${f##*.}" = txt ]; then printf '\e[1;31m%s\e[0m\n' "$f" elif [ "${f##*.}" = text ]; then printf '\e[1;34m%s\e[0m\n' "$f" elif [ "${f##*.}" = secret ]; then printf '\e[1;32m%s\e[0m\n' "$f" else printf '%s\n' "$f" fi done } 

Further reading:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.