0

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]
5

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
  • Thanks man. btw, could this work? .tar.gz 01;31 and .zip.gz 02;31 work? – Joe Theman Nov 10 '16 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). – Stephen Kitt Nov 10 '16 at 8:05
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:

Not the answer you're looking for? Browse other questions tagged or ask your own question.