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]
Kevdog777
  • 3,224
Joe Theman
  • 75
  • 1
  • 6

2 Answers2

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
Stephen Kitt
  • 434,908
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:

Wildcard
  • 36,499