3

Short question:

Using bash, is it possible to print a sentence such that each individual word has a different color?

I.e; print a word in-line, change the text color, repeat?

Graviton
  • 185
  • Do you mean customize colors at terminal? What is your ubuntu release? This can be useful to you – Redbob Sep 22 '17 at 17:03
  • @Redbob I'm currently using Ubuntu 14.04. And no. I want to print a sentence from a bash program that has a custom coloring without interfering with the rest of the text/profile. – Graviton Sep 22 '17 at 17:06
  • 2
  • @Redbob Exactly what I was looking for! – Graviton Sep 22 '17 at 17:13
  • Tks! I encourage you to develop this solution and post results as your answer. It will be useful and "maybe" more practical then the solution we indicated. – Redbob Sep 22 '17 at 17:15
  • Probably duplicate and already answered here https://stackoverflow.com/questions/5947742/how-to-change-the-output-color-of-echo-in-linux – ob2 Sep 22 '17 at 17:21
  • If you are going to use colors often, define them in .bashrc or I call .envrc as I use the same variables with zsh - http://bodhizazen.com/Tutorials/envrc . If you are wanting a portable script, often easiest to define colors at the top of the script . – Panther Sep 22 '17 at 17:38

1 Answers1

3

ANSI escape sequences

You can use ANSI escape sequences. It should work in text screens as well as most linux terminal window emulators.

See this link for details,

en.wikipedia.org/wiki/ANSI_escape_code

Example 1: White text on black background

echo -e "\0033[37;40m###############\0033[0m"

Example 2: Black text on greyish white background

echo -e "\0033[30;47m###############\0033[0m"

Example 3: Using the variables inversvid, greenback, blueback and resetvid

inversvid="\0033[7m"
resetvid="\0033[0m"
greenback="\0033[1;37;42m"
blueback="\0033[1;37;44m"
echo -e "$inversvid Now it is inverse colours $resetvid"
echo -e "$greenback Now it is greenback $resetvid and $blueback now blueback $resetvid"

enter image description here

Declare and store variables

Example of basic ANSI colour variables, that I use in bash shellscripts, and that you might find useful,

inversvid="\0033[7m"
resetvid="\0033[0m"
redback="\0033[1;37;41m"
greenback="\0033[1;37;42m"
blueback="\0033[1;37;44m"

Example of advanced ANSI colour variable (that almost matches the mkusb logo colour),

logoansi="\0033[38;5;0;48;5;148m"

The advanced ANSI colours work in most terminal window emulators, but not in text screens, where the colour defaults to 'the nearest basic colour'.


  • It is straightforward to declare and store the variables in a bash shellscript (near the beginning, at least before they are used).
  • If you want to use them interactively, you can declare and store the variables in the configuration file ~/.bashrc

And of course, you can create [modified] variables to perform what you want.

sudodus
  • 46,324
  • 5
  • 88
  • 152