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
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
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.
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
Example code is this.
In case you want to read more about regex, feel free to follow this link.
Let's say we want to remove all color codes here, I also prepared a function for that.
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
See sample output of colored and color-removed text.
Running in Shell
Similar to Python but have some details different.
This code stub below is just showing a part of the module in the repo.
source the file then it's ready. Also add
\033[0m ) to reset the color.
We use regex like Python but we can't use the same regex string.
\033 is non-printable character so we need to change a bit. The regex string for this case is
The regex string means not starting with printable characters, then be followed by
[, digits or commas, and ends with
sed to execute it with
-r flag means extended regex.
Here is the function for removing all color codes in Shell.
See sample output here.
- 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
2023-08-19: Update from "Bash" to "Shell" as this is not only available on Bash scripts but Shell scripts.