shell 腳本中的「友善」終端顏色名稱?

shell 腳本中的「友善」終端顏色名稱?

我知道 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

您可以使用tputprintf

使用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

在zsh中:

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}" ;

這是一個教程在終端機中列印彩色時鐘。

另請注意,將tputSTDOUT 重定向到檔案時仍可能列印轉義字元:

$ myColoredScript.sh > output.log ;
# Problem: output.log will contain things like "^[(B^[[m"

為了防止這種情況發生,請tput按照中建議的方式設定變量這個解決方案

相關內容