Pages

Friday, June 2, 2017

How to Customize Bash Colors and Content in Linux Terminal Prompt

Today, Bash is the default shell in most (if not all) modern Linux distributions. However, you may have noticed that the text color in the terminal and the prompt content can be different from one distro to another.
In case you have been wondering how to customize this for better accessibility or mere whim, keep reading – in this article we will explain how to do just that.

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):
$ echo $PS1
[\u@\h \W]\$
We will now explain how to customize PS1 as per our needs.

Customizing the PS1 Format

According to the PROMPTING section in the man page, this is the meaning of each special character:
  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.
For example, 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.
In the following example we will import both into our current environment by executing this command:
PS1="[\u@\H \W \!]\$"
When you press Enter you will see that the prompt content changes as shown below. Compare the prompt before and after executing the above command:
Customize Linux Terminal Prompt PS1
Customize Linux Terminal Prompt PS1
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.

      ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
                                                    ► Read more: http://adf.ly/1n5Yno
      ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

No comments:

Post a Comment