Offers: Zstack cloud computing
Content Introduction
Command-line operations are undoubtedly the most time-consuming process when managing Linux servers. For most users, this means a lot of time to manipulate the bash shell.
While most distributions offer default user types and root prompts, customizing our own prompt will undoubtedly help introduce more usage preferences. You can include a variety of practical information to help you perform tasks more specifically and be prompted for elevation of privilege.
In this example, we'll use Ubuntu 12.04 VPS, but almost all modern Linux distributions follow a similar approach.
Verify that your shell is bash
Before you start customizing the shell, you should confirm that your current shell is bash.
This is not a problem for most systems, but sometimes some versions may use different shells or have users use them to test new shells.
Check the/etc/passwd file to easily confirm this and first open the file:
less /etc/passwd
Each line in this file contains information that is relevant to different users. Find our users and root users in the first column, separated by colons. Within the last field, the default login shell is:
root:x:0:0:root:/root:/bin/bash. . .demouser:x:1000:1000:,,,:/home/demouser/bin/bash
If the last field is/bin/bash, the setting is complete.
If the last field is not/bin/bash and you want to change the default shell to bash, you can edit the file with root permission and change the last field associated with the user:
sudo nano /etc/passwd
After the change is complete, log out and return to use the bash shell.
View current values
First, let's look at what existing bash prompts definitions exist in the configuration file.
Bash uses PS1 and PS2 environment variables to configure its prompt.
PS1 is responsible for defining the main prompt we see. By default, the format of the Ubuntu system is as follows:
[email protected]: current_directory$
Note the $ number at the end of the list. This means that the shell belongs to the normal user shell. For the root user, the end is indicated by the # number.
PS2 prompt is used for multi-line commands. You can use the following command in the terminal to view the current PS2 variable:
Press ENTER directly to view the prompt. Typically, the variables we define are stored in the ~/.BASHRC file, which is read at the start of our interop Shell.
In the Ubuntu 12.04 file, we can find the following sections:
# uncomment for a colored prompt, if the terminal has the capability; turned# off by default to not distract the user: the focus in a terminal window# should be on the output of commands, not on the prompt# force_color_prompt=yesif [ -n "$force_color_prompt" ]; thenif [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then # We have color support; assume it‘s compliant with Ecma-48 # (ISO/IEC-6429). (Lack of such support is extremely rare, and such # a case would tend to support setf rather than setaf.) color_prompt=yeselse color_prompt=fifiif [ "$color_prompt" = yes ]; thenPS1=‘${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\[email protected]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ‘elsePS1=‘${debian_chroot:+($debian_chroot)}\[email protected]\h:\w\$ ‘fiunset color_prompt force_color_prompt
We are able to annotate part of the logic in a colored way. You need to uncomment the Force_color_prompt=yes line to implement the color prompt. There are other benefits to this approach, which we will discuss later in detail.
force_color_prompt=yes
What we need to focus on here is the section related to prompt settings. Whether to use color display depends on the nesting mechanism in IF-ELSE implementation:
if [ "$color_prompt" = yes ]; thenPS1=‘${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\[email protected]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ‘elsePS1=‘${debian_chroot:+($debian_chroot)}\[email protected]\h:\w\$ ‘fiunset color_prompt force_color_prompt
Color support is added to the above section. Let's look at the second part, first of all, exclude the color option to see the basic content:
PS1=‘${debian_chroot:+($debian_chroot)}\[email protected]\h:\w\$ ‘
Seems rather complex, and there are some parts that don't seem to be relevant to regular shell usage.
Where Debian_chroot represents whether we are operating in a change root environment, prompt will be modified to alert the user. You may need to keep this part of the tip.
The remainder of the prompt definition is:
This part is responsible for showing that we used a partial escape sequence in the main prompt.
Bash escape sequence
We can see the complete list of available escape sequences in the Bash Guide page:
\a an ASCII Bell character () \d the date in "Weekday Month date" format (e.g., "Tue may") \d{format} The Format is passed to Strftime (3) and the result was inserted into the prompt string; An empty format results in a locale-specific time representation. The braces is required\e an ASCII escape character (033) \h the hostname the first '. ' \h the Hostname\j the number of jobs currently managed by the shell\l of the shell ' s basename Dev Ice name\n newline\r Carriage return\s The name of the shell, the basename of $ (the portion following the fi NAL slash) \ t the current time in 24-hour HH:MM:SS format\t the current time in 12-hour HH:MM:SS format\@ the C Urrent time in 12-hour am/pm format\a the current time in 24-hour hh:mm format\u the username of the current user\ V The version of Bash (e.g, 2.00) \v The release of bash, version + patch level (e.g., 2.00.0) \w the current W Orking dirEctory, with $HOME abbreviated with a tilde (uses the value of the Prompt_dirtrim variable) \w The basename of the Curr ENT working directory, with $HOME abbreviated with a tilde\! The history number of this command\# the command number of this command\$ if the effective UID is 0, a #, Otherwis e a $\nnn the character corresponding to the octal number nnn\\ a backslash\[begin a sequence of non-printing C Haracters, which could is used to embed a terminal control sequence into the prompt\] end a sequence of non-printing C Haracters
As you can see, it contains some basic information, there are some information we don't use) ASCII Bell character, bash version, etc.).
Our prompt currently has a user name (\u), an @ symbol, the first part of the hostname (\h), the current working directory (\w), and the $ and # to label the normal user and root user.
Exit the ~/.BASHRC file below and test the other options.
Test the new bash prompts
Although we eventually need to edit the ~/.BASHRC file to adjust the selected parameters, it is obviously easier to test the effect directly from the command-line change prompt.
Before we begin to modify, we save the PS1 current value in a new variable. In this way, we can switch back to the original prompt at any time without having to sign out.
ORIG=$PS1
Now we have an environment variable named orig, which holds the default copy of prompt. If we need to switch back to the initial prompt, then:
PS1=$ORIG
Start with simple content and provide the user name and $ for the current prompt:
PS1="\u$"
The returned results are as follows:
demouser$
Add a space to improve the display:
PS1="\u $: "demouser $:
However, we may not want to use the $ character, where you can use the \$ escape sequence as an alternative. We can directly modify the PS1 with root privileges:
PS1="\u \$: "
Next, add any text characters you want to use in prompt:
PS1="Hello, my name is \u! \$: "Hello, my name is demouser! $:
We can also use the normal Shell function to insert arbitrary command execution results.
Here, we can insert the result of the command using an anti-quote, which extracts the first column of the load indicator from/PROC/LOADAVG, representing the current load of our server:
PS1="\u, load: `cat /proc/loadavg | awk ‘{ print $1; }‘` \$: "demouser, load: 0.01 $:
This makes it easy to understand the current intensity of the system's work.
If you want to focus on data or time in prompt, you can take similar actions. We need to share the data bits with parentheses and brackets, and add \w to ensure that only the current working directory is tracked:
PS1="[\[email protected]\h, load: `cat /proc/loadavg | awk ‘{ print $1; }‘`] (\d - \t) \w \$ "[[email protected], load: 0.01] (Thu Feb 20 - 13:15:20) ~ $
It is clear that the side-processing is cumbersome, especially if you need to make directory changes between long paths:
cd /etc/systemd/system/multi-user.target.wants[[email protected], load: 0.01] (Thu Feb 20 - 13:18:28) /etc/systemd/system/multi-user.target.wants $
If we still need complete information, but want to make the command shorter, you can use \ n to split the two lines of information:
PS1="[\[email protected]\h, load: `cat /proc/loadavg | awk ‘{ print $1; }‘`] (\d - \t)\n\w \$ "[[email protected], load: 0.00] (Thu Feb 20 - 13:20:00)/etc/systemd/system/multi-user.target.wants $
Some friends don't like to use multiline prompt, but it does allow our prompt to accommodate more information.
Change prompt color
Now that we've learned a variety of prompts adjustments, add a little bit of color to it next.
Bash allows us to use specific code to implement color display in prompt. But this usually brings new problems, because this part of the code is not clearly illustrated.
Before using color-coded code, we should first understand how the correct and wrong color code is defined in bash settings.
First of all, we must use [and] as a description of the color code range. For Bash, this represents a non-output character for a character between two brackets.
Bash needs to estimate the number of characters on this basis for future output. If you do not include the color code between [and], then bash will Fu Duji all the characters as text characters and package them in the next line.
In addition, in the non-output sequence in parentheses, we need to enter \e[or \033[to specify the starting point of the color prompt. Both have the same effect and are responsible for specifying the starting position of the antisense sequence. In this example, we will use \e[.
Before, we also need to use "M" to indicate that a color sequence is about to be provided.
Basically, every time we make color changes, we need to enter the following command format:
\[\e[color_informationm\]
As you can see, this will make our prompts quite messy.
Here's a basic code for changing the color of the foreground text:
- 30:black
- 31:red
- 32:green
- 33:yellow
- 34:blue
- 35:purple
- 36:cyan
- 37:white
You can also modify these base values by setting "Properties" before setting them, separating each value with a semicolon.
Depending on the actual terminal, the operation effect is also different. Some common properties include:
- 0: Normal text
- 1: May indicate bold or light colors in different terminals
- 4: Underlined text
So if you want to use the underlined green text, then:
\[\e[4;32m\]
Then continue to use it normally. In addition, we can reset the color to the initial value at any time.
The reset command is as follows:
\[\e[0m\]
In combination, the package contains the user name and the host's simple color prompt setup as follows:
PS1="\[\e[4;32m\]\[email protected]\h\[\e[0m\]$ "
We can also specify the background color. Background colors cannot get properties, including:
- 40:black background
- 41:red background
- 42:green background
- 43:yellow background
- 44:blue background
- 45:purple background
- 46:cyan background
- 47:white background
However, you can specify the background color, attributes, and text color at once:
\[\e[42;1;36m\]
Of course, it is recommended that you separate background information from other information:
\[\e[42m\]\[\e[1;36m\]
When using normal text attributes (0), some garbled characters may appear in the terminal. If this is the case, it is best to avoid specifying a normal property with a value of 0--we do not need to specify it because it belongs to the default value.
Permanently modify prompt
After a series of groping, I believe that we have a basic understanding of their favorite prompt should be what it looks like.
In this example, we will use the following color prompt:
PS1="[\[\e[0;32m\]\[email protected]\h, load: `cat /proc/loadavg | awk ‘{ print $1; }‘`\[\e[00m\]] (\[\e[00;35m\]\d - \t\[\e[00m\])\n\w \$ "
When you need to use a tone scheme, we choose the following configuration:
PS1="[\[email protected]\h, load: `cat /proc/loadavg | awk ‘{ print $1; }‘`] (\d - \t)\n\w \$ "
Now that we have two prompt versions ready, we'll edit the PS1 in the ~/.BASHRC file.
nano ~/.bashrc
As mentioned at the beginning of the article, each prompts in the file is included in the function for use in the chroot environment. This part of the content does not change, the contents of the document are as follows:
if [ "$color_prompt" = yes ]; thenPS1=‘${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\[email protected]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ‘elsePS1=‘${debian_chroot:+($debian_chroot)}\[email protected]\h:\w\$ ‘fiunset color_prompt force_color_prompt
Comment out the current PS1 allocation mechanism and copy the Debian_chroot logic underneath it, as follows:
if [ "$color_prompt" = yes ]; then# PS1=‘${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\[email protected]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ‘PS1=‘${debian_chroot:+($debian_chroot)}‘else# PS1=‘${debian_chroot:+($debian_chroot)}\[email protected]\h:\w\$ ‘PS1=‘${debian_chroot:+($debian_chroot)}‘fiunset color_prompt force_color_prompt
Before the last quotation mark at the end of the prompt, we can add each prompts that we want to implement. Also, because our prompt uses single quotes, we need to change the reference type in the current prompt to use double quotes.
Use the color version of prompt in the first PS1 assignment. In the second one, a monochrome version is used.
if [ "$color_prompt" = yes ]; then# PS1=‘${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\[email protected]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ‘PS1="${debian_chroot:+($debian_chroot)}[\[\e[0;32m\]\[email protected]\h, load: `cat /proc/loadavg | awk ‘{ print $1; }‘`\[\e[00m\]] (\[\e[00;35m\]\d - \t\[\e[00m\])\n\w \$ "else# PS1=‘${debian_chroot:+($debian_chroot)}\[email protected]\h:\w\$ ‘PS1="${debian_chroot:+($debian_chroot)}[\[email protected]\h, load: `cat /proc/loadavg | awk ‘{ print $1; }‘`] (\d - \t)\n\w \$ "fiunset color_prompt force_color_prompt
Save and exit when you are finished.
Now, when you log out and log back in, our prompt will change based on the value you set.
Summarize
We can personalize the configuration in a variety of ways, and color-coded display of specific items also helps to keep an eye on important content in the process.
Another popular practice is to provide the root user with special effect hints to remind you that you are currently in privileged mode of operation. Of course, you can also make the most of your imagination and help yourself to find truly interesting information in your chaotic work more efficiently.
This article originates from Digitalocean Community. Customize your Bash Prompt on a Linux VPS by Justin Ellingwood
Translation: DIRADW
How to customize your bash Prompt on a Linux VPS