colors in bash scripts
I have been trying to understand the color codes for bash for a pretty long time, but somehow never got time to understand this clearly. So this time around when I was writing a script to analyze some logs. I thought I will give it a go and finally understood some part of this.
So, first we will start with this script. This is taken from here.
#!/bin/bash - #=============================================================================== # # FILE: colortest.sh # # USAGE: ./colortest.sh # # DESCRIPTION: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html # # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Amit Agarwal (aka), amit.agarwal@roamware.com # COMPANY: # CREATED: 09/04/12 14:29:47 IST # Last modified: Sun Apr 15, 2012 06:29PM # REVISION: --- #=============================================================================== #!/bin/bash # # This file echoes a bunch of color codes to the # terminal to demonstrate what's available. Each # line is the color code of one forground color, # out of 17 (default + 16 escapes), followed by a # test use of that color on all nine background # colors (default + 8 escapes). # T='gYw' # The test text echo -e "\n 40m 41m 42m 43m\ 44m 45m 46m 47m"; for FGs in ' m' ' 1m' ' 30m' '1;30m' ' 31m' '1;31m' ' 32m' \ '1;32m' ' 33m' '1;33m' ' 34m' '1;34m' ' 35m' '1;35m' \ ' 36m' '1;36m' ' 37m' '1;37m'; do FG=${FGs// /} echo -en " $FGs \033[$FG $T " for BG in 40m 41m 42m 43m 44m 45m 46m 47m; #do echo -en "$EINS \033[$FG\033[$BG \$T \033[0m"; do echo -en " \033[$FG\033[$BG $T \033[0m"; done echo; done echo
This script will give you all the colors that are possible in the bash scripting. And now let’s understand color’s a little more.
There are basically two ways you can use colors and I will illustrate both with echo command.
Before we get into all these, we will see hot to reset the colors:
echo -e "\033[00m"
The first one is the one used in the above script, where in you can use the codes multiple times to get the desired effect. For example, see the screenshot below:
And the other way to achieve the same is to use all the color codes with one escape sequence :
Important to note here is that the “m” is missing.
All the codes that you want can be used separated by “;” and end with “m”. I think I have explained the things.
Related articles
- conky script used to monitor server status remotely. (amit-agarwal.co.in)
- Benchmarking the system/CPU performance (amit-agarwal.co.in)
- Bourne is not bash, or: Read, echo, and backslash (shebang.brandonmintern.com)
Related Articles:
- 2010/06/06 colors in bash – script to display all the possible colors.
- 2011/09/16 better bash debugging
- 2011/08/09 bash completion
- 2011/06/11 faster bash operations on files with File Descriptors.
- 2011/03/18 Try all colors in xterm with script before setting the color
Authored By Amit Agarwal
Amit Agarwal, Linux and Photography are my hobbies.Creative Commons Attribution 4.0 International License.