- Article pages now have a discussion option at the bottom (moderated/captcha, but no registration needed) - recently upgraded to a newer Dokuwiki version, please report problems

Terminal codes (ANSI/VT100) introduction

Terminal (control-)codes are needed to give specific commands to your terminal. This can be related to switching colors or positioning the cursor, simply everything that can't be done by the application itself.

How it technically works

A terminal control code is a special sequence of characters that is printed (like any other text). If the terminal understands the code, it won't display the character-sequence, but will perform some action. You can always print the codes with a simple echo command - for the application, it's nothing special.

Note: I see that codes referenced as "Bash colors" sometimes (several "Bash tutorials" etc…): That's a retarded and completely incorrect definition.

The tput command

Because there's a large number of different terminal control languages, usually a system has an intermediate-layer to talk to it. The real codes are looked up in a database for the currently detected terminal type and you give standardized requests to an API or (from the shell) to a command.

One of these commands is tput - it accepts a set of acronymes and parameters for them, looks up the correct codes for the detected terminal in the terminfo database and prints the correct codes (the terminal hopefully understands).

The codes

In this list I'll focus to ANSI/VT100 control codes for the most needed actions - take it as quick reference. The documentation of your terminal or the terminfo database is always the preferred source when something is unclear! Also the tput acronymes are the ones dedicated for ANSI escapes, usually!

Also I only listed the most relevant codes, of course, any ANSI or especially your nice terminal knows much more! But let's reduce to common shell scripting ;-)

Sometimes I didn't find a matching ANSI escape or vice versa - you'll see a :?: as code then - feel free to mail me or fix it!

The ANSI codes are always intoduced with an ESC character (ASCII 0x1B or octal 033) - this isn't part of the list, but you should avoid to use the ANSI codes directly - use the tput command!

All codes that can be used with tput can be found in terminfo(5). (on OpenBSD at least) See OpenBSD's terminfo(5) under the Capabilities section. The cap-name is the code to use with tput, a description of each code is also provided.

General useful ASCII codes

The Ctrl-Key representation is simply associating the non-printable characters from ASCII code 1 with the printable (letter) characters from ASCII code 65 ("A"). ASCII code 1 would be ^A (Ctrl-A), while ASCII code 7 (BEL) would be ^G (Ctrl-G). This is a common representation (and input method) and historically comes from one of the VT series of terminals.

NamedecimaloctalhexC-escapeCtrl-KeyDescription
BEL70070x07\a^GTerminal bell
BS80100x08\b^HBackspace
HT90110x09\t^IHorizontal TAB
LF100120x0A\n^JLinefeed (newline)
VT110130x0B\v^KVertical TAB
FF120140x0C\f^LFormfeed (also: New page NP)
CR130150x0D\r^MCarriage return
ESC270330x1B<none>^[Escape character
DEL1271770x7F<none><none>Delete character

Cursor handling

ANSIterminfo equivalentDescription
[ <X> ; <Y> H
[ <X> ; <Y> f
cup <X> <Y>Home-positioning to X and Y coordinates
:!: it seems that ANSI takes 1-1 as root while tput takes 0-0
[ HhomeHome-positioning to root (0-0)
8scSave current cursor position
9rcRestore current cursor position
:?: most likely a normal code like \bcub1move left one space (backspace)
VT100 [ ? 25 lcivisswitch cursor invisible
VT100 [ ? 25 hcvvisswitch cursor visible

Erasing text

ANSI terminfo equivalent Description
[ K
[ 0 K
el Clear line from current cursor position to end of line
[ 1 K el1 Clear line from beginning to current cursor position
[ 2 K el2:?: Clear whole line (cursor position unchanged)

General text attributes

ANSIterminfo equivalentDescription
[ 0 msgr0Reset all attributes
[ 1 mboldSet "bright" attribute
[ 2 mdimSet "dim" attribute
[ 4 mset smul unset rmul :?:Set "underscore" (underlined text) attribute
[ 5 mblinkSet "blink" attribute
[ 7 mrevSet "reverse" attribute
[ 8 minvisSet "hidden" attribute

Foreground coloring

ANSI terminfo equivalent Description
[ 3 0 m setaf 0 Set foreground to color #0 - black
[ 3 1 m setaf 1 Set foreground to color #1 - red
[ 3 2 m setaf 2 Set foreground to color #2 - green
[ 3 3 m setaf 3 Set foreground to color #3 - yellow
[ 3 4 m setaf 4 Set foreground to color #4 - blue
[ 3 5 m setaf 5 Set foreground to color #5 - magenta
[ 3 6 m setaf 6 Set foreground to color #6 - cyan
[ 3 7 m setaf 7 Set foreground to color #7 - white
[ 3 9 m setaf 9 Set default color as foreground color

Background coloring

ANSI terminfo equivalent Description
[ 4 0 m setab 0 Set background to color #0 - black
[ 4 1 m setab 1 Set background to color #1 - red
[ 4 2 m setab 2 Set background to color #2 - green
[ 4 3 m setab 3 Set background to color #3 - yellow
[ 4 4 m setab 4 Set background to color #4 - blue
[ 4 5 m setab 5 Set background to color #5 - magenta
[ 4 6 m setab 6 Set background to color #6 - cyan
[ 4 7 m setab 7 Set background to color #7 - white
[ 4 9 m setaf 9 Set default color as background color

Misc codes

Save/restore screen

Used capabilities: smcup, rmcup

For sure, you've already seen those programs that restore the terminal contents after they did their work (like vim). This can be done by the following codes:

# save, clear screen
tput smcup
clear

# example "application" follows...
read -n1 -p "Press any key to continue..."
# example "application" ends here

# restore
tput rmcup

Thanks to greycat for finding this and sharing it!

Bash examples

Hardcoded colors

Directly inside the echo:

echo -e 'It is \033[31mnot\033[39m intelligent to use \033[32mhardcoded ANSI\033[39m codes!'

With preset variables:

COL_NORM=$'\033[39m'
COL_RED=$'\033[31m'
echo "Beware, ${COL_RED}not all terminals${COL_NORM} support ANSI"

Colors using tput

Directly inside the echo:

echo "TPUT is a $(tput setaf 2)nice$(tput setaf 9) and $(tput setaf 5)user friendly$(tput setaf 9) terminal capability database."

With preset variables:

COL_NORM="$(tput setaf 9)"
COL_RED="$(tput setaf 1)"
COL_GREEN="$(tput setaf 2)"
echo "It's ${COL_RED}red${COL_NORM} and ${COL_GREEN}green${COL_NORM} - have you seen?"

Misc

HOME function

home() {
  # yes, actually not much shorter ;-)
  tput home
}

Silly but nice effect

#!/bin/bash

DATA[0]="     _/  _/    _/                            _/    "
DATA[1]="  _/_/_/_/_/  _/_/_/      _/_/_/    _/_/_/  _/_/_/ "
DATA[2]="   _/  _/    _/    _/  _/    _/  _/_/      _/    _/"
DATA[3]="_/_/_/_/_/  _/    _/  _/    _/      _/_/  _/    _/ "
DATA[4]=" _/  _/    _/_/_/      _/_/_/  _/_/_/    _/    _/  "

# virtual coordinate system is X*Y ${#DATA} * 5

REAL_OFFSET_X=0
REAL_OFFSET_Y=0

draw_char() {
  V_COORD_X=$1
  V_COORD_Y=$2

  tput cup $((REAL_OFFSET_Y + V_COORD_Y)) $((REAL_OFFSET_X + V_COORD_X))

  printf %c ${DATA[V_COORD_Y]:V_COORD_X:1}
}


trap 'exit 1' INT TERM
trap 'tput setaf 9; tput cvvis; clear' EXIT

tput civis
clear

while :; do

for ((c=1; c <= 7; c++)); do
  tput setaf $c
  for ((x=0; x<${#DATA[0]}; x++)); do
    for ((y=0; y<=4; y++)); do
      draw_char $x $y
    done
  done
done

done

Discussion

Lucas H, 2011/07/28 06:37

RE: your "Note: I found no code to entirely erase the current line ("delete line" is something else!). It might be a combination of positioning the cursor and erase to the end of line."

Try this: [ 2 K el2 Clear whole line

James, 2011/09/01 00:12

In the table showing

[ 3 9 m setaf 9 Set default foreground color

the Description "Set default foreground color" is ambiguous.

That phrase could mean either that the commands will 1) store the value of a specified color as the "default" color value, or that 2) a stored "default" color value will be used to re-set the current foreground or background color to a new value. Which is it? In one case there can be a visible change on the screen. In the other case, the will never be a visible change on the screen.

As it is, some people will create termcap files which gratuitously reset the display to the "default" colors, which makes using custom foreground and background colors impossible. Of course, this is just mean, and requires rewriting the termcap file.

Also, the Descriptions of the "Dim", "Bright", and "Reverse" attributes could actually say what these are suppose to do. For instance, what is suppose to happen when setting both "Dim" and "Bright"? Or, does "Reverse" apply to both the foreground and background colors? Does "Reverse" mean to exchange the foreground and background colors? Or to set some kind of "complement" color to each of the foreground and background?

These "Descriptions" that do not describe are not useful.

James

Constantine, 2011/09/21 14:43

# print shortcuts for all ansi codes, NB: please add plus plus in for statements!

      ansi-test()
      {
      for a in 0 1 4 5 7; do
              echo "a=$a " 
              for (( f=0; f<=9; f++ )) ; do
                      for (( b=0; b<=9; b++ )) ; do
                              #echo -ne "f=$f b=$b" 
                              echo -ne "\\033[${a};3${f};4${b}m"
                              echo -ne "\\\\\\\\033[${a};3${f};4${b}m"
                              echo -ne "\\033[0m "
                      done
              echo
              done
              echo
      done
      echo
      }
Aubrey Bourke, 2011/12/19 02:38

Hi,

Very cool tutorial. I recently purchased a beagleboard XM, so this site is a perfect place to start serial port programming.

And the "silly but nice effects" is awesome. I love it!

Here's a link to a "cool splash screen for my website". Its just a Java animation... (open with Java web start - jws)

file:///home/aubrey/Downloads/circlescroller.jnlp

Best Regards.

Jan Schampera, 2011/12/21 12:35

Hi,

thank you :-)

I don't think this link will work for anybody except you (file:) :-)

Enter your comment
 
scripting/terminalcodes.txt · Last modified: 2011/10/22 08:20 by thebonsai
GNU Free Documentation License 1.3
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0