Paint Terminal with Shell color codes
We as programmers are definitely familiar with Terminal. But printing on console would be boring in colors as black and white. So we will talk how to make console more colorful.
Here is an example.
Shell color codes
Terminal console works with texts. You can figure we now add some texts to decorate, Yes we just add a code to command Terminal to display mapped colors from the code.
The code is in the format \033[...m
.
In this blog we will see how to use it because I have already prepared the code for both Python and Shell scripts.
However, you can reach out to my repo here as a shortcut.
Running in Python
module
In the repo, I have created a class of constants of shell color codes. It looks as below.
This code stub is just showing a part of the module in the repo.
usage
To utilize the class is to import and add in the string as you want. Please note that the color code will affect until the end of string or applying default color code as this name is RESET
( \033[0m
).
Example code is this.
In case you want to read more about regex, feel free to follow this link.
clear
Let's say we want to remove all color codes here, I also prepared a function for that.
We use re
library and replace with .sub()
. In here we apply regex r"\033\[[\d;]+m"
which means starting with \033[
followed by digits or commas and ends with m
.
Output
See sample output of colored and color-removed text.
Running in Shell
Similar to Python but have some details different.
module
This code stub below is just showing a part of the module in the repo.
usage
We can source
the file then it's ready. Also add RESET
( \033[0m
) to reset the color.
clear
We use regex like Python but we can't use the same regex string.
Because \033
is non-printable character so we need to change a bit. The regex string for this case is [^[:print:]]\[[0-9;]+m
.
The regex string means not starting with printable characters, then be followed by [
, digits or commas, and ends with m
.
We use sed
to execute it with -r
flag means extended regex.
Here is the function for removing all color codes in Shell.
Output
See sample output here.
References
- How do I print colored text to the terminal? https://stackoverflow.com/questions/287871/how-do-i-print-colored-text-to-the-terminal
- Replace non-printable characters in perl and sed https://unix.stackexchange.com/a/201753
Edits
2023-08-19: Update from "Bash" to "Shell" as this is not only available on Bash scripts but Shell scripts.