Differences between revisions 6 and 7
Revision 6 as of 2008-12-02 12:16:55
Size: 1656
Editor: Lhunath
Comment: lowercase vars convention.
Revision 7 as of 2010-05-11 05:23:58
Size: 1644
Editor: p5B09615D
Comment: fixed links
Deletions are marked like this. Additions are marked like this.
Line 30: Line 30:
See also [[http://bash-hackers.org/wiki/doku.php?id=scripting:terminalcodes]] for an overview. See also [[http://wiki.bash-hackers.org/scripting/terminalcodes]] for an overview.

How can I print text in various colors?

Do not hard-code ANSI color escape sequences in your program! The tput command lets you interact with the terminal database in a sane way:

  # Bourne
  tput setaf 1; echo this is red
  tput setaf 2; echo this is green
  tput bold; echo "boldface (and still green)"
  tput sgr0; echo back to normal

tput reads the terminfo database which contains all the escape codes necessary for interacting with your terminal, as defined by the $TERM variable. For more details, see the terminfo(5) man page.

tput sgr0 resets the colors to their default settings. This also turns off boldface (tput bold), underline, etc.

If you want fancy colors in your prompt, consider using something manageable:

  # Bash
  red=$(tput setaf 1)
  green=$(tput setaf 2)
  blue=$(tput setaf 4)
  reset=$(tput sgr0)
  PS1='\[$red\]\u\[$reset\]@\[$green\]\h\[$reset\]:\[$blue\]\w\[$reset\]\$ '

Note that we do not hard-code ANSI color escape sequences. Instead, we store the output of the tput command into variables, which are then used when $PS1 is expanded. Storing the values means we don't have to fork a tput process multiple times every time the prompt is displayed; tput is only invoked 4 times during shell startup. The \[ and \] symbols allow bash to understand which parts of the prompt cause no cursor movement; without them, lines will wrap incorrectly.

See also http://wiki.bash-hackers.org/scripting/terminalcodes for an overview.

BashFAQ/037 (last edited 2023-10-01 21:59:10 by larryv)