在Bash中定制炫酷的命令提示符

如果你使用的是Linux桌面(例如:Fedora或者Ubuntu)的话,在Terminal上使用Bash通常是必须地,但是默认的Bash提示符都很普通。本文将提供简单的Bash脚本(通过定制PS1)定制炫酷的命令提示符(注: 绝非奇技淫巧)。

  • 脚本代码 - foo.bashrc
 1    COLOR_GRAY='[33[1;30m]'
 2     COLOR_RED='[33[1;31m]'
 3   COLOR_GREEN='[33[1;32m]'
 4  COLOR_YELLOW='[33[1;33m]'
 5    COLOR_BLUE='[33[1;34m]'
 6 COLOR_MAGENTA='[33[1;35m]'
 7    COLOR_CYAN='[33[1;36m]'
 8   COLOR_WHITE='[33[1;37m]'
 9    COLOR_NONE='[33[m]'
10 
11 PS1_USER="${COLOR_MAGENTA}u${COLOR_NONE}"
12 PS1_HOST="${COLOR_CYAN}h${COLOR_NONE}"
13 PS1_PWD="${COLOR_YELLOW}w${COLOR_NONE}"
14 
15 export PS1="${PS1_USER}@${PS1_HOST}:${PS1_PWD}\$ "
  • 效果图

  •  说明

01 -foo.bashrc添加到你的.bashrc文件中就可以使用炫酷的PS1了,当然,你也可以根据你的偏好自己设定PS1

02 - 在颜色定制文本(例如: COLOR_GRAY='[33[1;30m]')中,开始的[和结尾的]是必须的,否则当输入的命令很长的时候,就会回车但不换行,于是覆盖了行首的有颜色的字符串。例如:

P.S. 上面的诡异问题曾经困扰我了很多年,直到我偶然发现了[]的特殊作用。 我们期望的是另起一行,正确的输出行为应该是这样子滴,

但是,通过Bash编程在Terminal上输出彩色的字符串,是不能添加[]的。 例如:

function print { printf -- "$*
"; }

function _isatty
{
    typeset -l isatty=${ISATTY:-"auto"}
    [[ $isatty == "yes" ]] && return 0         # yes
    [[ $isatty == "no" ]] && return 1          # no
    [[ -t 1 && -t 2 ]] && return 0 || return 1 # auto
}

function str2gray    { _isatty && print "33[1;30m$@33[m" || print "$@"; }
function str2red     { _isatty && print "33[1;31m$@33[m" || print "$@"; }
function str2green   { _isatty && print "33[1;32m$@33[m" || print "$@"; }
function str2yellow  { _isatty && print "33[1;33m$@33[m" || print "$@"; }
function str2blue    { _isatty && print "33[1;34m$@33[m" || print "$@"; }
function str2magenta { _isatty && print "33[1;35m$@33[m" || print "$@"; }
function str2cyan    { _isatty && print "33[1;36m$@33[m" || print "$@"; }
function str2white   { _isatty && print "33[1;37m$@33[m" || print "$@"; }

完整代码文件libstr.sh请戳这里

Don't believe what your eyes are telling you. All they show is limitation. Look with your understanding. | 不要相信眼睛告诉你的。眼睛展现的内容是有限的。用你的悟性来观察。 
原文地址:https://www.cnblogs.com/idorax/p/8270025.html