Archive

Posts Tagged ‘PS1’

终端提示符的配置

August 9th, 2010 9 comments

原来一直对终端命令提示符感到不满, 默认就是没什么特别颜色, 想回去看命令时输出与命令混在一起, 一直以为是终端模拟器问题, 从gnome-terminal换成其它也一样, 后来发现这篇文章 <8个实用而有趣Bash命令提示行> #1(原文在此#2)原来是设置PS1变量的问题, 在~.bashrc 里面相应位置加入/换成如下代码:

1
2
3
4
5
6
7
8
if [ $color_prompt=yes ]; then
    PS1='\n\[\e[1;31m\][\w]\[\e[0m\] \[\e[1;35m\][ \[\e[1;36m\]$(/bin/ls -1 | /usr/bin/wc -l | /bin/sed "s: ::g") files \[\e[1;33m\]$(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed "s/total //")b\[\e[0m\] \[\e[1;35m\]]\n`a=$?;if [ $a -ne 0 ]; then echo -ne "\[\e[01;36;41m\]{$a}"; fi`\[\e[01;36m\][\t \u]\[\e[00m\] \[\e[01;34m\]\W`[[ -d .git ]] &amp;&amp; echo -ne "\[\e[33;40m\](branch:$(git branch | sed -e "/^ /d" -e "s/* \(.*\)/\1/"))\[\e[01;32m\]\[\e[00m\]"`\[\e[01;34m\] \$ \[\e[00m\]'
    # PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='\n[\w] [ $(/bin/ls -1 | /usr/bin/wc -l | /bin/sed "s: ::g") files $(/bin/ls -lah | /bin/grep -m 1 total | /bin/sed "s/total //")b ]\n`a=$?;if [ $a -ne 0 ]; then echo -ne "{$a}"; fi`[\t \u] \W`[[ -d .git ]] &amp;&amp; echo -ne "(branch:$(git branch | sed -e "/^ /d" -e "s/* \(.*\)/\1/"))"` \$ '
    # PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt

效果如下:

其中, 为2行, 第一行2个中括号中间分别是 完整路径, 文件数(包括文件夹不含隐藏文件)与文件大小(不包括子文件夹的大小). 第二行是日期, 用户名, 当前文件夹, 如果是git目录话会加上branch信息(此处代码参考Ai.Freedom的文章#3), 然后是提示符, root为# 普通用户为$ 如图.

如果文章到此了, 你肯定自己抓狂不然就是想弄死我了… 因为提供的参考文章与此文都是不讲原理只有效果的. 那代码一坨在那,看着就想死. 而且自己无法定制. 然后经过这2天的乱搞, 终于理清如下:

1. 其实控制提示符变量不止PS1, 还有PS2, PS3, PS4 和PROMPT_COMMAND, 参见 #4
2. 引号内容主要为 命令行提示符的反斜杠转义字符 #5
3. 其中有许多 \e[31m \033[34;40;7m 这种抓狂的东西, 是很老的终端机VT100的转义符, 此网页#6最后有说明, 简要说明下就是 \e 与 \033 是一个东西, 都是Escape 033的8进制在ASCII里面代表ESC. 格式:"\033[字背景颜色;字体颜色m字符串" 来控制颜色,高亮等.

最后说一句, 代码对于可以用有颜色的终端与不能的 分别设了PS1, 对就then 与 else下的代码, else的代码用 正则替换then中等到, 表达式为:
\\\[.*?\\\]

References:

#1: 8个实用而有趣Bash命令提示行 http://coolshell.cn/?p=1399
#2: 8 Useful and Interesting Bash Prompts http://maketecheasier.com/8-useful-and-interesting-bash-prompts/2009/09/04
#3: Ai.Freedom的PS1的git配置 http://aifreedom.com/technology/155
#4: PS1, PS2, PS3..的说明 http://www.thegeekstuff.com/2008/09/bash-shell-take-control-of-ps1-ps2-ps3-ps4-and-prompt_command/
#5: 命令行提示符的反斜杠转义字符 http://www.unixresources.net/linux/clf/newbie/archive/00/00/19/80/198022.html
#6: VT100终端控制序列 http://www.unixresources.net/linux/clf/newbie/archive/00/00/19/80/198022.html

Categories: Linux Tags: , , , , ,