Bash Colors and Content in Linux Terminal Prompt

The PS1 Bash Environment Variable

The command prompt and terminal appearance are governed by an environment variable called PS1. According to the Bash man page, PS1 represents the primary prompt string which is displayed when the shell is ready to read a command.

The allowed content in PS1 consists of several backslash-escaped special characters whose meaning is listed in the PROMPTING section of the man page.

To illustrate, let’s display the current content of PS1 in our system (this may be somewhat different in your case):

PS1 Format

PROMPTING section in the man page:

  1. \u: the username of the current user.
  2. \h: the hostname up to the first dot (.) in the Fully-Qualified Domain Name.
  3. \W: the basename of the current working directory, with $HOME abbreviated with a tilde (~).
  4. \$: If the current user is root, display #, $ otherwise.

We may want to consider adding \! If we want to display the history number of the current command, or \H if we want to display the FQDN instead of the short server name.

We will import both into our current environment by executing this command:

When you press Enter you will see that the prompt content changes as shown below.

Now let’s go one step further and change the color of the user and hostname in command prompt — both the text and its surrounding background.

Text Format Foreground (text) color Background color 0: normal text 30: Black 40: Black 1: bold 31: Red 41: Red 4: Underlined text 32: Green 42: Green 33: Yellow 43: Yellow 34: Blue 44: Blue 35: Purple 45: Purple 36: Cyan 46: Cyan 37: White 47: White

We will use the \e special character at the beginning and an m at the end to indicate that what follows is a color sequence.

Since the value ranges are different, it does not matter which one (background, format, or foreground) you specify first.

Change Linux Terminal Color Prompt PS1

As good as it looks, this customization will only last for the current user session. If you close your terminal or exit the session, the changes will be lost.

In order to make these changes permanent, you will have to add the following line to ~/.bashrc or ~/.bash_profile depending on your distribution:

Originally published at .