Custom Shell Prompt

Source: Internet
Author: User
Tags control characters echo command

In this chapter we'll look at a seemingly trivial detail-our shell. This examination would reveal some of the inner working of the shell and the terminal emulator program itself.

Many things in linux,the shell prompt was highly configurable,and while we had pretty much taken it for granted,th E prompt is a really useful device once we learn how to control it.

Anatomy (anatomy) of A Prompt

Our default prompt looks something like this:

Notice that it contains we user Name,our host name and our current working directory,but do it get that? Very Simply,it turns out. The prompt is defined by a environment variable named PS1 (short for "prompt string One"). We can view the contents of PS1 with the echo command:

Note:don ' t worry if your results is not exactly the same as the example above. Every Linux distribution defines the prompt string a little differently,some quite exotically.

From the results,we can see the PS1 contains a few of the characters we see in our prompt such as the brackets (brackets), the A T-sign,and the dollar sign,but The rest is a mystery. The astute (astute) among us'll recognize these as backslash-escaped special characters like those we saw in Chapter 8.Here is a partial list of the characters, the shell treats specially in the prompt string:

Table 14-1:escape Codes used in Shell prompts

Sequence Value Displayed
\a ASCII Bell. This makes the computer beep if it is encountered.
\d Current date in day,month,date format. For example, "Mon May 26."
\h Host name of the local machine minus the trailing domain name. (host name of the local machine, but without the end of the domain name)
\h Full host name.
\j Number of jobs running in the current shell session.
\l Name of the current terminal device.
\ n A newline character.
\ r A carriage return. (a carriage return character)
\s Name of the shell program.
\ t Current time in hour hours:minutes:seconds format.
\ t Current time in hour format
\@ Current time in hour am/pm format.
\a Current time in hour hours:minutes format.
\u User name of the current user.
\v Version number of the shell.
\v Version and release numbers of the shell
\w Name of the current working directory.
\w Last parts of the current working directory name. (The final part of the currently working directory name)
\! History number of the current command.
\# Number of commands entered into the this shell session.
\$ This displays a "$" character unless you have superuser privileges. In that Case,it displays a "#" instead.
\[

Signals the start of a series of one or more non-printing characters. This was used to embed non-printing control characters with manipulate (skilled control) the terminal emulator in some Way,such as Movi ng the cursor or changing text colors.

(marks the beginning of a series of one or more nonprinting characters.) This is used to embed nonprinting control characters that somehow manipulate the terminal emulator, such as moving the cursor or changing the color of the text.

\] Signals the end of a non-printing character sequence. (marks the end of a non-printable character sequence.) )

Trying Some Alternate Prompt Designs

With this list of special characters,we can, the prompt to see the effect. First,we ' ll back up the existing string so we can restore it later. To do this,we would copy the existing string into another shell variable that we create ourselves:

We Create a new variable called Ps1_old and assign the value of PS1 to it. We can verify that the string have been copied with the echo command:

We can restore the original prompt at any time during our terminal session by simply reversing the process:

Now that we're ready to proceed (go ahead, proceed, continue), let's see what happens if we had an empty prompt string:

If we assign nothing into the prompt string,we get nothing. No prompt string at all! The prompt is still there,but displays nothing,just as we asked it to (as we requested). Since This is kind of disconcerting (confused, uneasy) to the look at, we'll replace it with a minimal prompt:

That ' s better. At least now we can see how we are doing. Notice The trailing space within the double quotes. This provides the space between the "dollar sign" and the "cursor" when the prompt is displayed.

Let's add a bell to our prompt:

Now we should hear Beep, the prompt is displayed. This could get annoying,but it might is useful if we needed notification when a especially long-running command has been Executed.

Next,let's try to make a informative prompt with some host name and time-of-day information:

Try out the other sequences listed in the table above and see if you can come up with a brilliant new prompt.

Adding Color

Most terminal emulator programs respond to certain non-printing character sequences to control such things as character at Tributes (like Color,bold text and the dreaded blinking text) and cursor position. We ' ll cover cursor position in a little bit,but first we'll look at color.

Terminal confusion

Back in ancient (ancient, old, old, ancient people) Times,when terminals were hooked to remote Computers,there were many competing brands of T Erminals and they all worked differently. They had different keyboards and they all had different ways of interpreting (explained) control information. Unix and Unix-like systems have a rather complex subsystems to deal with the Babel of Terminal control (called Termcap an D terminfo). If you look in the deepest recesses of your terminal emulator settings you could find a setting for the type of terminal EMU Lation.

In a effort to make terminals speak some sort of common language,the American National Standards Institute (ANSI) develope D a standard set of character sqeuences to control video terminals. Old Time DOS users would remember the ANSI. SYN file that is used to enable interpretation of these codes.

!!!!!!!!!!!!!!!!!!!!!! This section of IQ is not enough, I really can't understand

Character color is controlled by sending the terminal emulator a ANSI escape code embeded in the stream of characters to Be displayed. The control code does not ' print out ' on the display,rather it was interpreted by the terminal as an instruction (command, instruction). As we saw in the table above,the [and] sequences is used to encapsulate non-printing characters. An ANSI escape code embedded in the stream of characters to be displayed. The control code does not ' print out ' on the display,rather it was interpreted by the terminal as an instruction. As we saw in the table above,the [and] sequences is used to encapsulate non-printing characters. An ANSI escape code begins with a octal 033 (the code generated by the escape key) followed by an optional character Attri Bute followed by an instruction. For example,the code to set the text color to normal (attribute = O), black text is:

Here is a table of available text colors. Notice that the colors is divided into and groups,differentiated by the application of the Bold character attribute (1) WH Ich creates the appearance of "Light" colors:

Table 14-2:escape sequences used to Set Text Colors

Sequence Text Color Sequence Text Color
\033[0;30m Black \033[1;30m Dark Gray
\033[0;31m Red \033[1;31m Light Red
\033[0;32m Green \033[1;32m Light Green
\033[0;33m Brown \033[1;33m Yellow
\033[0;34m Blue \033[1;34m Light Blue
\033[0;35m Purple \033[1;35m Light Purple
\033[0;36m Cyan \033[1;36m Light Cyan
\033[0;37m Light Gray \033[1;37m White

Let's try to make a red prompt. We ll insert the escape code at the beginning:

That works,but notice, all the text, the we type after the prompt is also red. To fix this,we would add another escape code to the end of the prompt that tells the terminal emulator to return to the pre Vious Color:

That works,but notice, all the text, the we type after the prompt is also red. To fix this,we would add another escape code to the end of the prompt that tells the terminal emulator to return to the pre Vious Color:

That ' s better!

It ' s also possible to set the text background color using the codes listed below. The background colors don't support the bold attribute.

Table 14-3:escape sequences used to Set

Background Color

\033[0;40m Blue \033[1;44m Black
\033[0;41m Red \033[1;45m Purple
\033[0;42m Green \033[1;46m Cyan
\033[0;43m Brown \033[1;47m Light Gray

We can create a prompt with a red background by applying a simple change to the first escape code:

Try out the color codes and see what can create!

Note:besides the normal (0) and bold (1) character Attributes,text may also be given underscore (4), blinking (5), and Inverse ( 7) attributes as well. In the interests of good Taste,many terminal emulators refuse to honor the blinking attribute,however.

Moving the Cursor

Escape codes can used to position the cursor. This was commonly used to provide a clock or some other kind of information at a different location on the screen such as a n Upper corner Each time the prompt is drawn. Here's a list of the escape codes that position the cursor:

Table 14-4:cursor Movement Escape sequences

Escape Code Action
\033[l;ch Move the cursor to line L and column C.
\033[na Move the cursor up n lines.
\033[nb Move the cursor down n lines.
\033[nc Move the cursor forward n characters.
\033[nd Move the cursor backward n characters.
\033[2j Clear the screen and move the cursor to the upper left corner (line 0, column 0).
\033[k Clear from the cursor position to the end of the "current" line.
\033[s Store the current cursor position.
\033[u Recall the stored cursor position.

Using the Codes above,we ' ll construct a prompt that draws a red bar at the top of the screen containing a clock (rendered I n Yellow text) each time the prompt is displayed. The code for the prompt are this formidable (scary, daunting) looking string:

Squence Action
\[ Begins a non-printing character sequence. The real purpose of this was to allow bash to correctly calculate the size of the visible (pronounced) prompt. Without This,command line editing features would improperly position the cursor.
\033[s Store the cursor position. The needed to return to the prompt location after the bar and clock has been drawn at the top of the. Be aware that some terminal emulators does not honor this code.
\033[0;0h Move the cursor to the upper left Corner,which was line Zero,column zero.
\033[0;41m Set the background color to red.
\033[k Clear from the current cursor location, the top left corner, to the end of the line. Since The background color is now red,the line was cleared to that color creating our bar. Note that clearing to the end of the line does the the cursor Position,which remains in the upper left corner.
\033[1;33m Set the text color to yellow.
\ t Display the current time. While this is a "printing" element,we still include it in the non-printing (Forbidden Printing) portion (part, one copy) of the prompt,since we do n ' t want Bash to include the clock when calculating the true size of the displayed prompt.
\033[om Turn off color. This affects both the text and background.
\033[u Restore the cursor position saved earlier.
\] End non-printing characters sequence.
<\[email protected]\h\w>\$ Prompt string.

Saving the Prompt

Obviously,we don ' t want to be typing this monster all the time,so we'll want to store our prompt someplace. We can make the prompt permanent (permanent, fixed) by adding it to our. bashrc file. To do so,add these-lines to the file:

Summing up

Believe it or not,there is much more then can be do with prompts involving shell functions and scripts that we haven ' t C Overed Here,but This is a good start. Not everyone would care enough to the Prompt,since the default prompt is usually satisfactory. But for those of the Tinker,the Shell provides the opportunity for many hours of trivial (unimportant, trivial, trivial) fun.

Custom shell prompt

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.