![shell 腳本中的「友善」終端顏色名稱?](https://rvso.com/image/50599/shell%20%E8%85%B3%E6%9C%AC%E4%B8%AD%E7%9A%84%E3%80%8C%E5%8F%8B%E5%96%84%E3%80%8D%E7%B5%82%E7%AB%AF%E9%A1%8F%E8%89%B2%E5%90%8D%E7%A8%B1%EF%BC%9F.png)
我知道 Ruby 和 Javascript 等語言的函式庫可以透過使用「紅色」等顏色名稱來更輕鬆地對終端腳本進行著色。
但是 Bash、Ksh 或其他語言中的 shell 腳本是否有類似的東西呢?
答案1
您可以在 bash 腳本中定義顏色,如下所示:
red=$'\e[1;31m'
grn=$'\e[1;32m'
yel=$'\e[1;33m'
blu=$'\e[1;34m'
mag=$'\e[1;35m'
cyn=$'\e[1;36m'
end=$'\e[0m'
然後使用它們以您需要的顏色進行列印:
printf "%s\n" "Text in ${red}red${end}, white and ${blu}blue${end}."
答案2
您可以使用tput
或printf
使用tput
,
只需創建如下函數並使用它們
shw_grey () {
echo $(tput bold)$(tput setaf 0) $@ $(tput sgr 0)
}
shw_norm () {
echo $(tput bold)$(tput setaf 9) $@ $(tput sgr 0)
}
shw_info () {
echo $(tput bold)$(tput setaf 4) $@ $(tput sgr 0)
}
shw_warn () {
echo $(tput bold)$(tput setaf 2) $@ $(tput sgr 0)
}
shw_err () {
echo $(tput bold)$(tput setaf 1) $@ $(tput sgr 0)
}
你可以使用呼叫上面的函數shw_err "WARNING:: Error bla bla"
使用printf
print red; echo -e "\e[31mfoo\e[m"
答案3
autoload -U colors
colors
echo $fg[green]YES$fg[default] or $fg[red]NO$fg[default]?
答案4
更好的是使用tput
它將根據輸出/終端功能處理轉義字元。 (如果終端無法解釋\e[*
顏色代碼,那麼它將被“污染”,這使得輸出難以閱讀。(或者有時,如果您grep
這樣輸出,您將\e[*
在結果中看到這些)
看到這個教學tput
。
你可以寫 :
blue=$( tput setaf 4 ) ;
normal=$( tput sgr0 ) ;
echo "hello ${blue}blue world${normal}" ;
這是一個教程在終端機中列印彩色時鐘。
另請注意,將tput
STDOUT 重定向到檔案時仍可能列印轉義字元:
$ myColoredScript.sh > output.log ;
# Problem: output.log will contain things like "^[(B^[[m"
為了防止這種情況發生,請tput
按照中建議的方式設定變量這個解決方案。