《学渣Linux笔记》——更改ls命令的输出颜色和命令提示符颜色(二)

《学渣Linux笔记》——更改ls命令的输出颜色和命令提示符颜色(二)

II.更改命令提示符颜色

命令提示符的显示格式是由变量PS1决定的,首先我们查找GNU官方手册,发现如下内容(不是我喜欢写一大段,只是希望能养成查阅官方手册的习惯):

The value of the variable PROMPT_COMMAND is examined just before Bash prints each primary prompt. If PROMPT_COMMAND is set and has a non-null value, then the value is executed just as if it had been typed on the command line.

In addition, the following table describes the special characters which can appear in the prompt variables PS0, PS1, PS2, and PS4:

\a
A bell character.

\d
The date, in "Weekday Month Date" format (e.g., "Tue May 26").

\D{format}
The format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required.

\e
An escape character.

\h
The hostname, up to the first ‘.’.

\H
The hostname.

\j
The number of jobs currently managed by the shell.

\l
The basename of the shell’s terminal device name.

\n
A newline.

\r
A carriage return.

\s
The name of the shell, the basename of $0 (the portion following the final slash).

\t
The time, in 24-hour HH:MM:SS format.

\T
The time, in 12-hour HH:MM:SS format.

\@
The time, in 12-hour am/pm format.

\A
The 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 + patchlevel (e.g., 2.00.0)

\w
The current working directory, with $HOME abbreviated with a tilde (uses the $PROMPT_DIRTRIM variable).

\W
The basename of $PWD, with $HOME abbreviated with a tilde.

\!
The history number of this command.

\#
The command number of this command.

\$
If the effective uid is 0, #, otherwise $.

\nnn
The character whose ASCII code is the octal value nnn.

\\
A backslash.

\[
Begin a sequence of non-printing characters. This could be used to embed a terminal control sequence into the prompt.

\]
End a sequence of non-printing characters.

我们好像找不到我们想要的颜色选项,怎么办呢?我记得别人的是可以改颜色的呀!这时我想到了家目录下的.bashrc文件。让我打开看看:
$cat ~/.bashrc
然后我找到了这一段:

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ 

这一段里面好像只有[\033[01;32m]这段看不懂,再结合上一篇的内容,01、34这些是不是可能就是颜色代码呢?还真是!经过试验,我得到命令提示符的颜色选项格式如下:

开头:\[\033[F;B;Cm\]
结尾:\[\033[00m\]

注:为什么多了个C?结合上一篇,我们可以知道颜色设定有三个参数可以用此处亦是如此。此外,一旦出现结束符,后面的颜色选项将不会生效,类似于字符串输出时遇到'\0'。
我现在的PS1变量是什么样的呢?如下:

\033[32;40;1m\u@\h:\e[33;40m\W\033[0m$
有点不一样对吧?仔细看看上面附带的那一大段,里面有个“[”和“]”,是不打印出来的,于是经过试验,发现省去也可以(但是003与颜色代码之间的[不可以省,注意一下就可以发现,它少了个反斜杠,并不是非打印字符)。

猜你喜欢

转载自www.cnblogs.com/ZEROPONG/p/11843097.html