
나는 "red"와 같은 색상 이름을 사용하여 터미널 스크립트를 더 쉽게 색상화할 수 있도록 Ruby 및 Javascript와 같은 언어로 된 라이브러리를 알고 있습니다.
하지만 Bash나 Ksh 등의 쉘 스크립트에 이와 같은 것이 있습니까?
답변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
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"
답변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
제안된 대로 변수를 설정하세요.이 솔루션.