シェルスクリプト内の「わかりやすい」ターミナルカラー名


25

RubyやJavascriptなどの言語のライブラリを認識しており、「赤」などの色名を使用して端末スクリプトの色付けを容易にします。

しかし、BashやKshなどのシェルスクリプトにはこのようなものがありますか?


8
答えを正解としてマークしてください。これまでに合計46の質問のうち1つだけをマークしました。
m13r 14

回答:


39

次のように、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}."

11

tput OR を使用できます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"

2
echo -eではないprintf、ともそれが異なっていることを警告必要tputが自動的にスーツに適応していないことでオプションを$TERM
トビーSpeight


4

単純な一般的な使用(単一行のみのテキストのフルライン、末尾の改行)のために、jasonwryanのコードを次のように変更しました

#!/bin/bash

red='\e[1;31m%s\e[0m\n'
green='\e[1;32m%s\e[0m\n'
yellow='\e[1;33m%s\e[0m\n'
blue='\e[1;34m%s\e[0m\n'
magenta='\e[1;35m%s\e[0m\n'
cyan='\e[1;36m%s\e[0m\n'

printf "$green"   "This is a test in green"
printf "$red"     "This is a test in red"
printf "$yellow"  "This is a test in yellow"
printf "$blue"    "This is a test in blue"
printf "$magenta" "This is a test in magenta"
printf "$cyan"    "This is a test in cyan"

または、Awkで、わずかに変更:awk -v red="$(printf '\e[1;31m%%s\e[0m\\n')" -v green="$(printf '\e[1;32m%%s\e[0m\\n')" 'BEGIN { printf red, "This text is in red"; printf green, "This text is in green" }'
ワイルドカード

3

より良いのは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は、このソリューションで提案されているように変数を設定します。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.