operating_system:nix_colors_in_terminal
目錄表
[*nix] Colors in Terminal
0x00 前言
在 terminal 中我們常會希望一些輸出可以帶有顏色,例如: shell prompt, motd 等,除了賞心悅目,方便我們閱讀,也更快速聚焦到重點的部分
本篇介紹如何在 terminal 中使用色碼輸出
0x01 Escape Sequences
這是我們用來輸出色碼的序列,由 ESC
開頭
而 ESC 是一個 Escape character,一般 bash 中有三種方式可以編碼
- Shell:
\e
- ASCII Hex:
\0x1B
- ASCII Oct:
\033
而 ESC 輸出通常會表示為 ^[
或 <ESC>
用 vim 或 cat -v 通常會看到 ^[ 或 <ESC>,這是 ESC non-printable 的字元表示法,
若用 vim 編輯直接輸入 ^[ 或是 \033 等上面三種編碼只會被當成一般文字,無法起作用
若要將 Escape Sequences 寫進 file,我們需要先用 print or echo 將它以 non-printable char 輸出後再做 pipe
0x02 Control Sequence Introducer
這是 Escape Sequences 的第一個部分,由 ESC
character 和一個 [
組成
0x03 Color codes
這是 Escape Sequences 的第二個部分
前面控制顏色,後面控制格式
Color
code | color |
---|---|
30 | Black |
31 | Red |
32 | Green |
33 | Yellow |
34 | Blue |
35 | Magenta |
36 | Cyan |
37 | White |
Format
code | format |
---|---|
1 | bold |
2 | dim |
3 | italics |
4 | underline |
7 | Background |
0x03 Finishing symbol
這是 Escape Sequences 的第三個部分
m character 表示這個 Escape Sequences 至此結束
需要注意的是當設了Escape Sequences,後面的文字皆會受其影響
若要只對特定文字設置,在文字後需要再以 \x1b[0m
將配置清空
0x04 參考資料
operating_system/nix_colors_in_terminal.txt · 上一次變更: 由 127.0.0.1