ney*_*rec 35 bash prompt escape-characters
我在一些屏幕截图(不记得网络上的哪个位置)中看到终端可以[username@machine /]$用粗体显示。我也很期待得到这个,因为我总是发现自己在长输出中滚动,很难找到我命令后的第一行。
如何使用户名等为粗体或彩色?
jw0*_*013 47
找到PS1您的位置.bashrc并'\[\e[1m\]'在开头和\[\e[0m\]结尾插入。
\[并且\]是必要的,所以外壳知道里面的混乱在屏幕上占用了 0 空间,这可以防止在进行行编辑时出现一些搞砸的行为。你不必太担心它。\e[被称为 CSI(控制序列引入器)。您会看到它在引用的 Wikipedia 页面上列出的大多数代码中使用。\e 表示转义字符。CSI 1m打开粗体并CSI 0m重置字体,以便文本的其余部分正常。维基百科有一个完整的 ANSI 转义码列表,如果您的终端模拟器支持,您可以使用它。
为了可移植性和可读性,您应该使用tput而不是硬编码转义码。唯一的缺点是该tput方法不适用于支持 ANSI 代码但有损坏或缺少 terminfo 数据库的终端,但在这种情况下,损坏的 terminfo 是一个更大的问题,因为许多依赖 terminfo 的控制台应用程序可能无法正常工作。
这是我在我的工作中所做的一个例子.bashrc:
# color names for readibility
reset=$(tput sgr0)
bold=$(tput bold)
black=$(tput setaf 0)
red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
blue=$(tput setaf 4)
magenta=$(tput setaf 5)
cyan=$(tput setaf 6)
white=$(tput setaf 7)
user_color=$green
[ "$UID" -eq 0 ] && { user_color=$red; }
PS1="\[$reset\][\[$cyan\]\A\[$reset\]]\[$user_color\]\u@\h(\l)\
\[$white\]:\[$blue\]\W\[$reset\][\[$yellow\]\$?\[$reset\]]\[$white\]\
\\$\[$reset\] "
Run Code Online (Sandbox Code Playgroud)
这是我的通用版本的样子。在0为最后一个命令的退出状态。

小智 24
您应该能够通过PS1在~/.bashrc文件中设置提示变量来做到这一点,如下所示:
PS1='[\u@\h \w]\$ '
Run Code Online (Sandbox Code Playgroud)
要使其着色(并且可能是粗体 - 这取决于您的终端模拟器是否已启用它),您需要添加转义颜色代码:
PS1='\[\e[1;91m\][\u@\h \w]\$\[\e[0m\] '
Run Code Online (Sandbox Code Playgroud)
在这里,没有在1;91m和0m部分之间转义的所有内容都将以1;91颜色(粗体红色)着色。将这些转义码放在提示的不同部分以使用不同的颜色,但请记住用 重置颜色,0m否则您也会有彩色的终端输出。请记住在之后获取文件以更新当前的 shell:source ~/.bashrc
这是您在 cygwin bash shell 中获得的默认提示:
PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ '
Run Code Online (Sandbox Code Playgroud)

\[\e]0;\w\a\] = Set the Window title to your current working directory
\n = new line
\[\e[32m\] = Set text color to green
\u@\h = display username@hostname
\[\e[33m\] = Set text color to yellow
\w = display working directory
\[\e[0m\] = Reset text color to default
\n = new line
\$ = display $ prompt
Run Code Online (Sandbox Code Playgroud)
参考:
man bash并检查该PROMPTING部分。