custom shell prompt

本文详细介绍了如何在Linux中配置个性化的Shell提示符,包括显示用户名、主机名、当前目录等信息,并通过特殊字符实现时间显示、命令计数等功能。此外,还介绍了如何使用ANSI转义序列设置文本颜色及背景色,以及如何移动光标实现屏幕布局的自定义。

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

Like so many things in Linux,the shell prompt is highly configurable,and while we have pretty much taken it for granted,the prompt is a really useful device once we learn how to control it.

 

Anatomy(解剖) Of A Prompt

Our default prompt looks something like this:

Notice that it contains our user name,our host name and our current working directory,but how did it get that way?Very simply,it turns out.The prompt is defined by an 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 are 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(中括号), the at-sign,and the dollar sign,but the rest are a mystery.The astute(机敏的) among us will recognize these as backslash-escaped special characters like those we saw in Chapter 8.Here is a partial list of the characters that the shell treats specially in the prompt string:

Table 14-1:Escape Codes Used In Shell Prompts

SequenceValue Displayed
\aASCII bell.This makes the computer beep when it is encountered.
\dCurrent date in day,month,date format.For example,"Mon May 26."
\hHost name of the local machine minus the trailing domain name.(本地机的主机名,但不带末尾的域名)
\HFull host name.
\jNumber of jobs running in the current shell session.
\lName of the current terminal device.
\nA newline character.
\rA carriage return.(一个回车符)
\sName of the shell program.
\tCurrent time in 24 hour hours:minutes:seconds format.
\TCurrent time in 12 hour format
\@Current time in 12 hour AM/PM format.
\ACurrent time in 24 hour hours:minutes format.
\uUser name of the current user.
\vVersion number of the shell.
\VVersion and release numbers of the shell
\wName of the current working directory.
\WLast part of the current working directory name.(当前工作目录名的最后部分)
\!History number of the current command.
\#Number of commands entered into 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 is used to embed non-printing control characters with manipulate(熟练控制) the terminal emulator in some way,such as moving the cursor or changing text colors.

(标志着一系列一个或多个非打印字符的开始。这被用来嵌入非打印的控制字符,这些字符以某种方式来操作终端仿真器,比方说移动光标或者是更改文本颜色)

\]Signals the end of a non-printing character sequence.(标志着非打印字符序列结束。)

Trying Some Alternate Prompt Designs

With this list of special characters,we can change the prompt to see the effect.First,we'll back up the existing string so we can restore it later.To do this,we will 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 has 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 are ready to proceed(前进,进行,继续下去),let's see what happens if we have an empty prompt string:

If we assign nothing to 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(正如我们要求的那样).Since this is kind of disconcerting(困惑的,不安的) to look at ,we'll replace it with a minimal prompt:

That's better.At least now we can see what 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 each time the prompt is displayed.This could get annoying,but it might be useful if we needed notification when an especially long-running command has been executed.

Next,let's try to make an 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 attributes(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(古代的,古老的,老人,古代人) times,when terminals were hooked to remote computers,there were many competing brands of terminals and they all worked differently.They had different keyboards and they all had different ways of interpreting(解释)control information.Unix and Unix-like systems have two rather complex subsystems to deal with the babel of terminal control(called termcap and terminfo).If you look in the deepest recesses of your terminal emulator settings you may find a setting for the type of terminal emulation.

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

!!!!!!!!!!!!!!!!!!!!!!这一段智商不够,表示真心看不懂

 

Character color is controlled by sending the terminal emulator an ANSI escape code embeded in the stream of characters to be displayed.The control code does not"print out" on the display,rather it is interpreted by the terminal as an instruction(命令,指示).As we saw in the table above,the [ and ] sequences are 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 is interpreted by the terminal as an instruction.As we saw in the table above,the [ and ] sequences are used to encapsulate non-printing characters.An ANSI escape code begins with an octal 033(the code generated by the escape key) followed by an optional character attribute 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 are divided into two groups,differentiated by the application of the bold character attribute(1) which creates the appearance of "light" colors:

Table 14-2:Escape Sequences Used To Set Text Colors

SequenceText ColorSequenceText Color
\033[0;30mBlack\033[1;30mDark Gray
\033[0;31mRed\033[1;31mLight Red
\033[0;32mGreen\033[1;32mLight Green
\033[0;33mBrown\033[1;33mYellow
\033[0;34mBlue\033[1;34mLight Blue
\033[0;35mPurple\033[1;35mLight Purple
\033[0;36mCyan\033[1;36mLight Cyan
\033[0;37mLight Gray\033[1;37mWhite

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

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

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

That's better!

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

Table 14-3:Escape Sequences Used To Set

Background Color

\033[0;40mBlue\033[1;44mBlack
\033[0;41mRed\033[1;45mPurple
\033[0;42mGreen\033[1;46mCyan
\033[0;43mBrown\033[1;47mLight 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 you 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 be used to position the cursor.This is commonly used to provide a clock or some other kind of information at a different location on the screen such as an upper corner each time the prompt is drawn.Here is a list of the escape codes that position the cursor:

Table 14-4:Cursor Movement Escape Sequences

Escape CodeAction
\033[l;cHMove the cursor to line l and column c.
\033[nAMove the cursor up n lines.
\033[nBMove the cursor down n lines.
\033[nCMove the cursor forward n characters.
\033[nDMove the cursor backward n characters.
\033[2JClear the screen and move the cursor to the upper left corner (line 0, column 0).
\033[KClear from the cursor position to the end of the current line.
\033[sStore the current cursor position.
\033[uRecall 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 in yellow text ) each time the prompt is displayed.The code for the prompt is this formidable(可怕 的,令人畏惧的) looking string:

SquenceAction
\[Begins a non-printing character sequence.The real purpose of this is to allow bash to correctly calculate the size of the visible(明显的) prompt.Without this,command line editing features will improperly position the cursor.
\033[sStore the cursor position.This is needed to return to the prompt location after the bar and clock have been drawn at the top of the screen.Be aware that some terminal emulators do not honor this code.
\033[0;0HMove the cursor to the upper left corner,which is line zero,column zero.
\033[0;41mSet the background color to red.
\033[KClear from the current cursor location(the top left corner)to the end of the line.Since the background color is now red,the line is cleared to that color creating our bar.Note that clearing to the end of the line does not change the cursor position,which remains at the upper left corner.
\033[1;33mSet the text color to yellow.
\tDisplay the current time.While this is a "printing" element,we still include it in the non-printing(禁止打印的) portion(一部分,一份)of the prompt,since we don't want bash to include the clock when calculating the true size of the displayed prompt.
\033[omTurn off color.This affects both the text and background.
\033[uRestore the cursor position saved earlier.
\]End non-printing characters sequence.
<\u@\h\W>\$Prompt string.

 

 Saving The Prompt

Obviously,we don't want to be typing that monster all the time,so we'll want to store our prompt someplace.We can make the prompt permanent(永久性的,固定的) by adding it to our  .bashrc file.To do so,add these two lines to the file:

Summing Up

Believe it or not,there is much more that can be done with prompts involving shell functions and scripts that we haven't covered here,but this is a good start.Not everyone will care enough to change the prompt,since the default prompt is usually satisfactory.But for those of us who like to tinker,the shell provides the opportunity for many hours of trivial(不重要的,琐碎的,琐细的) fun.

 

转载于:https://www.cnblogs.com/itmeatball/p/7594136.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值