Wednesday, May 16, 2012

Print color text in command line

Sometimes echo is not enough, if you need to print more advanced format of text. Lucky, we have printf. printf is a common function call in c programming language, if you learn c before, you should very familiar with this function.

Simply illustrate the power of printf, do as follow:

printf '\n\t\thello\tworld\n'
 

Besides readable character, printf can accept unreadable character too in octal value, hex value etc. That we can inject color setting to ask printf to print text in color.

printf '\x1b\x5b1;31;40m\tMerry Christmas\n'
 
 
\x1b\x5b is actually hex code 1B and 5B, this trailing is use to change the graphics display setting.
1;31;40m is actually the part of changing text attribute,fore color and background color.

But this leave a side effect, the settings stay after the printf. To return it back to normal, set back to foreground white and backgroud black.

printf '\x1b\x5b1;31;40m\tMerry Christmas\n\x1b\x5b0;37;40m'
 

P/S: For color code, refers to reference link.

This somehow leave it like a stain if your console is in pseudo transparent, to make it nice, I add more stuff in.

clear;printf '\x1b\x5b1;31;40m\tMerry Christmas\n\x1b\x5b0;37;40m';read;ls;clear
 

This is a stupid hack! You can actually do better. First I clear the screen, then print the stuff I want and set back the setting, wait for an user enter by using read, simply run ls ( this is to get back pseudo transparent at gnome-terminal) and at last clear screen again.

You can move your cursor before printing the text,

clear;printf '\x1b\x5b12;25f\x1b\x5b1;31;40m\tMerry Christmas\n\x1b\x5b0;37;40m';read;ls;clear
 

With the same hex code, add in 12;25f , 12 is the row, 25 is the column. I end the example here and wish you Merry Christmas, check out the reference for the trick!

Reference:
ANSI CODES

PS:
this article come from
http://linux.byexamples.com/archives/184/print-text-in-colors-with-a-simple-command-line/

版权声明
本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者Saturn和本文原始地址:
https://ndtm-idea.blogspot.com/2012/05/print-color-text-in-command-line.html

0 comments:

Post a Comment