Jump to content

Formatting output on the console via ANSI escape sequences

- - - - -

  • Please log in to reply
1 reply to this topic

#1
PhillipKessels

PhillipKessels

    Newbie

  • Members
  • Pip
  • 8 posts
This is my first tutorial here, so please forgive me all my mistakes :D;).

Ok, first of all: This is ~platformdependent. Your system is possibly not able to interprete ANSI escape codes. I was able to do this under Mac OS X Snow Leopard.

First of all a little example:
Type
echo -e '\033[31m This is some nice red text'

So, how does this work?
I assume you know the echo builtin command ;). The '-e' option tells bash to treat '\033' (octal ascii code, see ASCII - Wikipedia, the free encyclopedia) as the escape character (ESC), the magic character, we use to do all the formatting. The bad thing about all that is, that it might be that it only works for me. You have to find a way to print the escape character to the console to introduce an ascape code. Maybe some guys on the forum know how to do that on your platform or (if you're lucky) it simply works.

Ok, let's go on:
For now we know, that '\033' is ESC, but that doesn't format our text. We need to add CSI (Control Sequence Introducer), a symbol which tells the console to treat the following sequence as a escape code (who would have guessed that? ;) ). This symbol is '['. Now we simply add some code from this table.

There are several possibilities to format your text, have a look at it.

Try:
echo -e '\033[4;31m This is underlined and coloured'
You can combine the numerical parameters via ';'. I used number 4 for the underlining and 31 for the red colour (have a look here).
So for graphical modification of the text, the syntax is:

Quote

CSI n [;k] m
,
what means nothing else as (for me):
'\033[am'
The m indicates that the escape sequence is of the Select Graphic Rendition kind.
a is a list of arguments or a single argument (all numbers).
'[' is the CSI.



All that stuff wasn't to complicated, but I think something like this would have helped me a lot to understand how the escape sequences work.

#2
PhillipKessels

PhillipKessels

    Newbie

  • Members
  • Pip
  • 8 posts
U can use this technique in programming languages which print on a console as well (as long as the console is able to interprete the escape codes; dont even try on the eclipse console ), for example:
System.out.println((char)27+"[31mThis is some nice text.");





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users