Color your Bash Prompt

Menu

How to color the Bash prompt

To color the Bash prompt, you can set the PS1 variable (primary prompt) to something like:

export PS1="\[\033[38;5;COLOR_CODEm\]PROMPT\[\033[39m\] "

where

  • COLOR_CODE is an integer specifying a color
  • PROMPT is what you want to show on the prompt

Thus, for instance:

export PS1="\[\033[38;5;1m\]\u@\h$\[\033[39m\] "

colors the prompt green, since 1 is the color code for green and shows the current user and host \u@\h.

What color is 23?

Well, this depends on the terminal type. The function I use to list the available colors is the following:

# list all colors
function list_colors {
  for i in {1..255}; do
      echo -en "\033[38;5;${i}m[color ${i}]\033[39m"
  done
  echo ""
}

And this is the output I get on my terminal:

list-colors.png

Easily Change the Color of your Prompt

We can now put everything together with the following code, which I use to control the color you my prompt:

# this a B/W prompt for dumb terminals (e.g. Emacs shell)!
$DUMB_PROMPT="\u@\h$ "

# this is a function to color the prompt
function color_prompt {
    COLOR=$1
    export PS1="\[\033[38;5;${COLOR}m\]${DUMB_PROMPT}\[\033[39m\]"
}

And this is an example of its usage:

colored-prompt.png

More Information

The Arch Linux Wiki provides a very detailed guide on this topic: Bash/Prompt Customization.

Author: Adolfo Villafiorita

Last modified: 2020-08-28 Fri 21:08 (created on: 2014-11-09 Sun 00:00)

Published: 2020-12-04 Fri 13:21