作者:Thorbjørn Ravn Andersen | 譯者:Chou-Kai Wang | v1.4(1997)
現代彩色顯示器普及,使用者期望終端機以色彩區分檔案類型、程式關鍵字、拼字錯誤等。Linux 文字模式控制台支援 ANSI 色碼,GNU ls 早已整合彩色輸出(Slackware 2.0 起),現為所有發行版標準配備。本文說明多種設定方法,並提供較新 xterm 取得來源。
修改使用者家目錄下的 Shell 設定檔,下次登入生效:
# ~/.bashrc alias ls="ls --color" # ~/.cshrc / ~/.tcshrc alias ls 'ls --color'
進階:自訂顏色對應表:
eval `dircolors $HOME/.colourrc`
產生樣板:dircolors -p > $HOME/.colourrc,檔案含詳細註解可直接修改。
在 Linux 主控台或 xterm 執行:
ls --color
ls --version 確認版本 ≥ 3.13)。xterm 不支援 ANSI 色碼,需升級 xterm(見第 6 節)。ls 3.13 運作正常。執行以下腳本顯示主控台支援的顏色組合:
#!/bin/bash
esc="\033["
echo -n " 40 41 42 43 44 45 46 47"
for fore in 30 31 32 33 34 35 36 37; do
line1="$fore "
line2=" "
for back in 40 41 42 43 44 45 46 47; do
line1="${line1}${esc}${back};${fore}m Normal ${esc}0m"
line2="${line2}${esc}${back};${fore};1m Bold ${esc}0m"
done
echo -e "$line1\n$line2"
done
前景色碼(左欄):30 黑、31 紅、32 綠、33 黃、34 藍、35 紫、36 青、37 白。背景色碼(上排):40-47 對應同色系。加 ;1 為粗體/高亮。完整序列:ESC[37;44;1m(白字藍底粗體)。背景無高亮,黃色僅能作前景。
產生並編輯 ~/.coloursrc:
cd; dircolors -p > .coloursrc
編輯後載入環境變數 LS_COLORS:
eval `dircolors .coloursrc`
將此行加入 .bashrc、.cshrc 或 .tcshrc。詳細語法見 dircolors(1)。
setterm -foreground black -background white -store
-store 將目前設定寫入終端機資料庫為預設值。需 TERM 環境變數對應的 termcap 記錄完整。
需支援彩色的 xterm 變體:
xterm -fg white -bg blue4 color_xterm -fg white -bg blue4 color-xterm -fg white -bg blue4 nxterm -fg white -bg blue4
color_xterm 支援彩色 ls,色彩風格仿 SGI。
編輯 /usr/src/linux/drivers/char/console.c 約第 1940 行:
def_color = 0x07; /* white on black */ ulcolor = 0x0f; /* bold white */ halfcolor = 0x08; /* grey */ → 改為例: def_color = 0x17; /* white on blue */ ulcolor = 0x1f; /* bold white on blue */ halfcolor = 0x18; /* grey on blue */
重編核心後生效。建議使用 kernel patch 方式維護修改。