最後更新: 2024-04-18
echo & escape
The -e option of the echo command enable the parsing of the escape sequences.
In Bash, the <Esc> character can be obtained with the following syntaxes:
- \e
- \033
- \x1B
Text Color & Reset
- black='\e[0;30m'
- white='\e[0;1;37m'
- dark_gray='\e[1;30m'
- light_gray='\e[0;37m'
- red='\e[0;31m'
- green='\e[0;32m'
- yellow='\e[0;33m'
- blue='\e[0;34m'
- magenta='\e[0;35m'
- cyan='\e[0;36m'
Light
- Light Red 1;31
- Light Green 1;32
- Yellow 1;33
- Light Blue 1;34
- Light Purple 1;35
- Light Cyan 1;36
Reset attributes(color)
clear='\e[0m'
The ”\e[0m” sequence removes all attributes (formatting and colors)
Text Color Examples
echo -e "The color is: ${red}red${clear}!"
彩虹
for (( i = 30; i < 38; i++ )); do echo -e "\e[0;"$i"m Normal: (0;$i); \e[1;"$i"m Light: (1;$i)"; done; echo -e "\e[0m"
Text background color
- bg_red='\e[0;41m'
- bg_green='\e[0;42m'
- bg_yellow='\e[0;43m'
- bg_blue='\e[0;44m'
- bg_magenta='\e[0;45m'
- bg_cyan='\e[0;46m'
tput
The tput utility uses the terminfo database to make the values of terminal-dependent capabilities and
information available to the shell (see sh(1)), to initialize or reset the terminal,or
return the long name of the requested terminal type.
Tput produces character sequences that are interpreted by the terminal as having a special meaning.
Usage
- tput setab [1-7] # Set the background colour using ANSI escape
- tput setaf [1-7] # Set the foreground colour using ANSI escape
- tput sgr0 # Reset text format to the terminal's default
Num Colour #define R G B 0 black COLOR_BLACK 0,0,0 1 red COLOR_RED 1,0,0 2 green COLOR_GREEN 0,1,0 3 yellow COLOR_YELLOW 1,1,0 4 blue COLOR_BLUE 0,0,1 5 magenta COLOR_MAGENTA 1,0,1 6 cyan COLOR_CYAN 0,1,1 7 white COLOR_WHITE 1,1,1
i.e.
echo "$(tput setaf 1)Red text $(tput setab 7)and white background$(tput sgr 0)"
應用
redC=`tput setaf 1` greenC=`tput setaf 2` resetC=`tput sgr0` echo "${redC}red text ${greenC}green text${resetC}"