Hi there,
Yes, you can do that with the ANSI escape characters. You can find a list of those characters here.
For example, if you wanted to print green text, you could do the following:
#!/bin/bash
# Set the color variable
green='\033[0;32m'
# Clear the color after that
clear='\033[0m'
printf "The script was executed ${green}successfully${clear}!"
A quick rundown of the script:
- First we set the green color as a variable
- After that we set a variable called
clear
so that we could reset the color of the terminal, otherwise all of the output will be green.
- Then using
printf
we printout the message
Here is the output of the script:

If you prefer using echo
instead of printf
you need to make sure that you add the -e
flag:
#!/bin/bash
# Set the color variable
green='\033[0;32m'
# Clear the color after that
clear='\033[0m'
echo -e "The script was executed ${green}successfully${clear}!"
Here are some other common colors that you could:
#!/bin/bash
# Color variables
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
blue='\033[0;34m'
magenta='\033[0;35m'
cyan='\033[0;36m'
# Clear the color after that
clear='\033[0m'
# Examples
echo -e "The color is: ${red}red${clear}!"
echo -e "The color is: ${green}green${clear}!"
echo -e "The color is: ${yellow}yellow${clear}!"
echo -e "The color is: ${blue}blue${clear}!"
echo -e "The color is: ${magenta}magenta${clear}!"
echo -e "The color is: ${cyan}cyan${clear}!"
Output:

You can also change the text background with the following:
#!/bin/bash
# Color variables
bg_red='\033[0;41m'
bg_green='\033[0;42m'
bg_yellow='\033[0;43m'
bg_blue='\033[0;44m'
bg_magenta='\033[0;45m'
bg_cyan='\033[0;46m'
# Examples
echo -e "The background color is: ${red}red${clear}!"
echo -e "The background color is: ${green}green${clear}!"
echo -e "The background color is: ${yellow}yellow${clear}!"
echo -e "The background color is: ${blue}blue${clear}!"
echo -e "The background color is: ${magenta}magenta${clear}!"
echo -e "The background color is: ${cyan}cyan${clear}!"
Output:

Hope that this helps!
Regards,
Bobby