How-To среда: Цветной вывод ls
03.08.2007

По умолчанию, в Федореном Горе  команда ls подсвечивает файлы разными цветами, но не когда она вызывается из другой программы, а когда она вызывается из консоли. Пример:

$ ls -l /etc/sysconfig

auditd
authconfig
autofs
bittorrent
bluetooth
cbq
clock
console
cpuspeed
crond
dund
firstboot
grub
hidd
hsqldb
httpd
hwconf
hw-uuid
i18n
init
ip6tables-config
iptables-config
irda
irqbalance
kernel
keyboard
kudzu
libvirtd
lirc
livna-config-display
lm_sensors
modules
nasd
netconsole
network
networking
network-scripts
ntpd
oidentd
pand
prelink
readonly-root
samba
saslauthd
selinux
sendmail
smartmontools
spamassassin
squid
syslog
system-config-securitylevel
system-config-users
tux
vdr
vdr-plugins.d
vncservers
wpa_supplicant
xendomains
xinetd

Цвет файлов cbq, console, modules, networking, network-scripts и vdr-plugins.d — синий (директории), libvirtd и xendomains — зеленые (исполняемые файлы); selinux — бирюзовый (действующая символическая ссылка).
Вывод команды ls — цветной, потому что в системе задан альяс:

$ alias ls
alias ls='ls --color=tty'

Когда ls вызывается, опция –color=tty добавляется автоматически.

Текущая привязка цветов к файлам содержится в переменной окружения LS_COLORS, значение которой задается в скрипте /etc/profile.d/colorls.sh (или colorls.csh если используете шел csh). Этот скрипт, который также задает альясы команде ls, берет цвета из одного из следующих файлов: ~/.dir_colors.$TERM, ~/.dir_colors, ~/.dircolors.$TERM, ~/.dircolors, /etc/DIR_COLORS.$TERM, или /etc/DIR_COLORS (файлы перечислены в порядке уменьшения приоритета, переменная $TERM — переменная окружения).

Файл /etc/DIR_COLORS.xterm содержит следующие строки:


# Below are the color init strings for the basic file types. A color init
# string consists of one or more of the following numeric codes:
# 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
NORMAL 00 # global default, although everything should be something.
FILE 00 # normal file
DIR 01;34 # directory
LINK 01;36 # symbolic link
FIFO 40;33 # pipe
SOCK 01;35 # socket
BLK 40;33;01 # block device driver
CHR 40;33;01 # character device driver
ORPHAN 01;05;37;41 # orphaned syminks
MISSING 01;05;37;41 # ... and the files they point to

# This is for files with execute permission:
EXEC 01;32

# List any file extensions like '.gz' or '.tar' that you would like ls
# to colorize below. Put the extension, a space, and the color init string.
# (and any comments you want to add after a '#')
.cmd 01;32 # executables (bright green)
.exe 01;32
.com 01;32
.btm 01;32
.bat 01;32
.sh 01;32
.csh 01;32
.tar 01;31 # archives or compressed (bright red)
.tgz 01;31
.arj 01;31
.taz 01;31

и т.д.

Видим, что каждому типу и расширению файла соответствуют некоторые атрибуты и цвет. Коды цветов и атрибутов перечислены в комментариях файла.

Можно создать свою копию этого файла и настроить ее под себя:

 $ cp /etc/DIR_COLORS.xterm ~/.dir_colors.xterm

 Например, если нужно отображать файлы .doc как белый на пурпурном, в файл нужно добавить следующую строчку:

 .doc 01;37;45

что означает:

01 — атрибут «жирный»
37 — белые буквы
45 — пурпурный фон