"Friendly" terminal color names in shell scripts?
Solution 1
You can define colours in your bash scripts like so:
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'
And then use them to print in your required colours:
printf "%s\n" "Text in ${red}red${end}, white and ${blu}blue${end}."
Solution 2
You can use tput
OR printf
Using tput
,
just create function as below and use them
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)
}
you can call above function using shw_err "WARNING:: Error bla bla"
Using printf
print red; echo -e "\e[31mfoo\e[m"
Solution 3
autoload -U colors
colors
echo $fg[green]YES$fg[default] or $fg[red]NO$fg[default]?
Solution 4
For simple common uses (full line of text in a single color only, with trailing newline) I modified jasonwryan's code as follows:
#!/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"
Solution 5
Better is to use tput
which will handle escape characters depending on the output / terminal capabilities. (If a terminal cannot interpret \e[*
color codes, then it will be "polluted" which makes output harder to read. (Or sometimes, if you grep
such output, you will see those \e[*
in the results)
See this tutorial for tput
.
You can write :
blue=$( tput setaf 4 ) ;
normal=$( tput sgr0 ) ;
echo "hello ${blue}blue world${normal}" ;
Here is a tutorial to print a colored Clock in the terminal.
Also, note that tput
may still prints escape character when redirecting STDOUT to a file:
$ myColoredScript.sh > output.log ;
# Problem: output.log will contain things like "^[(B^[[m"
To prevent this to happen, setup your tput
variables like proposed in this solution.
Related videos on Youtube
themirror
Updated on September 18, 2022Comments
-
themirror almost 2 years
I'm aware of libraries in languages such as Ruby and Javascript to make colorizing your terminal scripts easier by using color names like "red".
But is there something like this for shell scripts in Bash, or Ksh, or whatever?
-
Stéphane Chazelas over 8 yearsAlso:
print -P '%F{red}blah%f'
-
Wildcard over 6 yearsOr in Awk, modified slightly:
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" }'