root时的红色终端字体

ron*_*ron 3 colors bash prompt root

我想在 RHEL/CentOS 7.6 中实现

每当您这样做su并成为 root 时,我希望该终端中的终端提示颜色在该su会话期间变为红色。键入exit以恢复原样,我希望提示颜色恢复为以前的颜色(黑色)。

对于使用通过网络登录的 putty 的 SSH 窗口也是如此:最初以用户身份 ssh并具有默认的白色 shell 提示;执行suroot 操作,我希望提示变为红色;输入 exit 我希望提示回到白色。

到目前为止,我这样做了,但它没有 100% 工作,在您键入exit并离开 su 会话并返回到用户状态后,颜色保持红色。

/etc/profile.d/red_root_prompt.sh

if [ $UID -eq 0 ]; then
   PS1="\e[31m[\u@\h \W]# "
else
   PS1="[\u@\h \W]# "
Run Code Online (Sandbox Code Playgroud)

有没有办法让事情按照我想要的方式发生?我只想要它用于 bash shell。

Net*_*ear 5

您可以将此添加到/etc/bash.bashrc或编辑/etc/profile/

force_color_prompt=yes

    if [ "$LOGNAME" = root ] || [ "`id -u`" -eq 0 ] ; then
        PS1='\[\033[01;31m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;34m\]#\033[00m\] '
    else
        PS1='\u@\h:\w\$ '
    fi
Run Code Online (Sandbox Code Playgroud)

你会得到一个看起来像这样的提示。如果您使用白色背景,请将最后一部分更改为#\033[01;30m\]以便您可以看到命令文本。我把它作为第二个例子供参考。

视觉外观

此外,如果您将以下内容添加到\etc\bash.bashrc或 ~/.bashrc:

export col_white='\033[00m'
export col_black='\033[01;30m'

export col_red='\033[01;31m'
export col_green='\033[01;32m'
export col_yel='\033[01;33m'
export col_blue='\033[01;34m'
Run Code Online (Sandbox Code Playgroud)

你将能够做到:

$ echo -e $col_red red $col_blue blue $col_yel yellow $col_green green
 red blue yellow green
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

在此处输入图片说明


编辑:出于某种原因,对提示使用变量扩展会中断回车(它将其锁定到变量的长度,即通过与echo $col_blue,对应的 n 个空格将其向前推echo $col_white,我还没有找到一个好的解决方案,因为此刻,但使用适当的括号而不使用变量替换如上所述解决了这个问题。

$ echo -e $col_red red $col_blue blue $col_yel yellow $col_green green
 red blue yellow green
Run Code Online (Sandbox Code Playgroud)