About ANSI control codes

ansiIntroduction

(loosely based on the perfect Bash Hackers Wiki)
Terminal (control-)codes are used 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.

 


1 Generalities about ANSI control codes

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

1.1 Escape character

  • Here are some “escape character” i encountered on various terminal emulator
    Note : You can find the type of terminal emulation by echoing the $TERM variable.
    Note #2 : Please note what theĀ  wiki.bash-hackers says about the direct use of ANSI control codes:
    You should avoid “direct use” of ANSI code in a terminal emulator, instead use the tputcommand […]As you can see in the Bash scripts examples post, even at a linux system level ANSI codes are directly used …

    • ubuntu terminal (GNOME Terminal 2.30.2): This terminal emulator requires the “\033[” escape character.
    • Red Hat terminal (Konsole): This terminal emulator requires the “\033[” escape character.

 

1.2 Simple example

  • Here is a simple example that show you how to use ANSI control codes
    1. Print your login in red (and get your terminal back to default color!):
      echo -e "\033[031m$(whoami)\033[0m"

 

1.3 Print ALL available ANSI code from your system

A little piece of code that prints out each and every ANSI code your system may understand.

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
Tagged on: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site supports SyntaxHighlighter via WP SyntaxHighlighter. It can highlight your code.
How to highlight your code: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag and format it when submitted.