更改Bash配置文件中提示符的颜色

5

我正在尝试将终端提示符的颜色更改为绿色文本,以便在开始时为用户提供白色~

目前,我的.bash_profile文件配置如下,为用户名提供黄色,为~提供粉色。

PS1='\e[33;1m\u@\h: \e[31m\W\e[0m\$'

有人知道如何修改上述代码以将颜色更改为绿色和白色吗?

哪个 shell 更好,bash 还是 zsh - chepner
我正在使用Bash /bin/bash - user6002037
4个回答

7
PS1='\e[32;1m\u@\h: \e[37m\W\e[0m\$'

[后面的数字是颜色代码。请参考此参考资料

真不错!传奇,谢谢!可以在2分钟内接受答案。 - user6002037
你知道如何在文件夹名称和美元符号之间加入空格吗?目前它看起来像这样 directory$ touch index.html - user6002037
1
PS1='\e[32;1m\u@\h: \e[37m\W\e[0m $' 应该输出为 directory $。(保留斜线和美元符号在一起。) - bishop

2
你想要改变 ANSI转义序列,特别是 颜色\e[...m接受一个分号分隔的代码列表,用于控制以下文本的显示方式。 33代表黄色前景文本,1代表粗体文本,31代表红色前景文本,而0则将所有值(前景和背景颜色、样式等)重置为终端默认值。
# Make text yellow and bold, then make it red (keeping it bold)
# and finally restore the default
PS1='\e[33;1m\u@\h: \e[31m\W\e[0m\$'

使用绿色/白色代替黄色/红色,将33改为32,31改为37。此外,请确保将不占屏幕空间的字符括在\[...\]中,以便shell可以正确确定提示符的长度。
PS1='\[\e[32;1m\]\u@\h: \[\e[37m\]\W\[\e[0m\]\$'

这假设您的终端理解 ANSI 转义序列;更具可移植性的方法是使用 tput 输出实际终端使用的代码:
PS1='\[$(tput bold; tput setaf 2)\u@\h: \[$(tput setaf y)\]\W$(tput sgr0)\$ '

顺便提一句,zsh 使得这个过程更加容易;它内置了可以在终端无关的方式下改变颜色的转义字符:
# 1. Everything between %B and %b is in bold
# 2. Everything between %F{x} and %f is in a different color;
#    x can be a color name, and you can switch from one
#    color to another without using %f
# 3. zsh is smart enough to account for built-in escapes when
#    computing the prompt lenght, so no equivalent of \[...\]
#    is needed
# 4. %n is the same as \u
# 5. %m is the same as \h
# 6. %~ is roughly the same as \W
# 7. %# is roughly the same as \$
PS1='%B%F{green}%n@%m: %F{white}%~%b%f%# '

谢谢@chepner!我已经给了你点赞,但是已经选定了最佳答案!还是感谢你的帮助。 - user6002037
如果你愿意的话,你可以更改答案(虽然我并不是说你需要这样做)。 - chepner

0

要更改每个部分提示符的颜色,请尝试使用这个简单的存储库:

https://github.com/joenmarz/bashrc-alias

您可以更改每个提示部分的颜色,例如:

  • 用户名
  • '@'符号
  • 主机名
  • 时间
  • 括号符号 '[' 和 ']'
  • 根指示器(# 表示 root 用户,$ 表示非 root 用户)

您的提示将如下所示:

[username@hostname 00:00 AM ~/working/directory $]

转到此文件的第 33 行 (bashrc-alias/.bashrc) 自定义每个提示部分的颜色变量:

  • open_brk_color - 更改开括号颜色
  • closed_brk_color - 更改闭括号颜色
  • at_color - 更改'@'符号颜色
  • username_color - 更改用户名颜色
  • hostname_color - 更改主机名颜色
  • time_color - 更改时间提示颜色
  • wd_color - 更改工作目录提示颜色
  • ri_color - 更改根指示器颜色

安装方法

  1. 将此存储库克隆到您的主目录下: git clone https://github.com/joenmarz/bashrc-alias
  2. 在现有的 ~/.bash 文件中添加文件路径: . /home/$USER/bashrc-alias/aliases
  3. 通过键入以下命令刷新您的 .bashrc 资源: source ~/.bashrc

我通过为每个提示部分添加一些变量使其更加简单。


0

这种方法比其他方法有两个好处:

  1. 它使用 \[\] 来括起转义序列,以避免在编辑换行后的行时出现字符计数问题。
  2. 它使用 tput 来更改颜色,使得正在执行的操作更加自我记录:

    PS1='\[$(tput setaf 2)\]\u@\h: \[$(tput setaf 7)\]\W\[$(tput sgr0)\]\$'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接