Shell – echo colored text which changes colors dynamically

echoscriptingshell-script

Is there any way that I can print a colored text on console which keeps on changing its colors dynamically(with or without a specified time interval) just like some greeting cards in which the greeting changes colors?

I am aware of printing a colored text using

echo eg: echo -e "\e[1;34m Hi dude, Welcome to the Matrix \e[0m" 

but I wish this text keeps changing color.

Is it actually possible?

Best Answer

You can't print text with instructions to change its colour repeatedly. You can write different-coloured text over the top of your original text, with something like this:

i=0
while true
do
    echo -en "\r\e[1;3${i}mWelcome to the Matrix\e[0m"
    i=$(((i+1)%8))
    sleep 0.25
done

That will cycle through all the bright colours, changing four times a second. \r is a carriage return, which moves the cursor back to the start of the line; echo -n suppresses the newline at the end of the output.

That only works for a single line, and the last line of output. You can also use a different set of escapes to move around a little more. \e[3A will move the cursor up three lines, and you can then rewrite the text up there again:

i=0
while true
do
    echo -e "\e[0;3$(((i+1)%8))mHello!\e[0m"
    echo -e "\e[1;3${i}mWelcome to the Matrix\e[0m"
    i=$(((i+1)%8))
    sleep 0.25
    echo -e "\e[3A"
done

That will write two lines in different colours, both changing constantly.

These are all ANSI escape codes, and there are a lot of them. If you're using them a lot then a library like curses is probably helpful. tput is also a handy tool, which is also more portable than using raw escape codes. If you are using the raw codes, B/C/D are down/right/left.

It isn't possible with these to have the changing text just "sit there" indefinitely. You can have a particular piece of text sit around indefinitely, with care, by putting the process into the background (with & or otherwise). It can move the cursor to the right place, rewrite the text, and then move it back. One example you may find useful, depending on what your end goal is, is the "clock" demonstration from the Bash prompt howto. With a lot of work and a cooperative terminal emulator you can get enough information back to make that text scroll normally, but it really isn't worthwhile.

Strictly I should note that there is a "blink" code, which does run in what you've called the "backend" and I suppose is technically a change of colour. It behaves like the <blink> tag, displaying and hiding the text every so often. It isn't universally supported: Konsole, xterm, the Linux console, and Apple Terminal do implement it, but others generally don't. It's code 5, in any case.

Related Question