我正在嘗試以 HTML 格式呈現 linux shell 命令的輸出。例如,systemctl status mysql在我的終端中看起來像這樣:

正如我從
在顯示文本“Active: failed”的第 080 行和第 090 行底部附近,我希望找到一些控制序列將顏色更改為紅色。雖然不一定是 ascii,但我使用了一些ascii 表來幫助我:
- 查看顯示字母的第 090 行的第二批 8 個字符
ive: fa,我發現: - 69 = 我
- 76 = v
- 65 = e
- 3a = :
- 20 = 空間
- 66 = f
- 61 = 一個
- 69 = 我
控制序列沒有位元組。
我想知道 hexyl 是否選擇不顯示它們,所以我撰寫了一個 Java 程式,該程式在將行程作為 bash 腳本執行后輸出原始位元組,結果是相同的 - 沒有控制序列。
Java大致是:
p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "systemctl status mysql"}); // runs in the shell
p.waitFor();
byte[] bytes = p.getInputStream().readAllBytes();
for(byte b : bytes) {
System.out.println(b "\t" ((char)b));
}
輸出:
...
32
32
32
32
32
65 A
99 c
116 t
105 i
118 v
101 e
58 :
32
102 f
97 a
105 i
108 l
101 e
100 d
...
所以問題是: bash 怎么知道它必須將“失敗”這個詞顯示為紅色?
uj5u.com熱心網友回復:
systemctl 檢測到輸出不是終端,并從輸出中洗掉顏色代碼。
相關:檢測標準輸入是終端還是管道?, https://unix.stackexchange.com/questions/249723/how-to-trick-a-command-into-thinking-its-output-is-going-to-a-terminal , https://superuser.com /questions/1042175/how-do-i-get-systemctl-to-print-in-color-when-being-interacted-with-from-a-non-t
工具有時(有時不)帶有始終啟用顏色代碼的選項,例如ls --color=always,grep --color=always在帶有SYSTEMD_COLORS環境變數的 systemd 的情況下啟用。
我可以使用什么工具來查看它們?
您可以使用hexyl來查看它們。
bash 怎么知道它必須將“失敗”這個詞標記為紅色?
Bash 是外殼,它是完全不相關的。
由于輸出中的 ANSI 轉義序列,您的終端(用于查看輸出的圖形視窗)知道將其標記為紅色。沒有與 Bash 的互動。
$ SYSTEMD_COLORS=1 systemctl status dbus.service | grep runn | hexdump -C
00000000 20 20 20 20 20 41 63 74 69 76 65 3a 20 1b 5b 30 | Active: .[0|
00000010 3b 31 3b 33 32 6d 61 63 74 69 76 65 20 28 72 75 |;1;32mactive (ru|
00000020 6e 6e 69 6e 67 29 1b 5b 30 6d 20 73 69 6e 63 65 |nning).[0m since|
00000030 20 53 61 74 20 32 30 32 32 2d 30 31 2d 30 38 20 | Sat 2022-01-08 |
00000040 31 39 3a 35 37 3a 32 35 20 43 45 54 3b 20 35 20 |19:57:25 CET; 5 |
00000050 64 61 79 73 20 61 67 6f 0a |days ago.|
00000059
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411857.html
標籤:
