【Linux】Bash的折衷美化方案——PS1

本文介绍了如何在Ubuntu和CentOS系统中统一ZSH和Bash的配置,包括安装ZSH、Oh My ZSH,以及自定义Bash提示符和颜色方案。通过修改默认配置文件,可以实现新用户账户的一致性设置,提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自 GNOME40 尝鲜以来已许久再未摸过桌面发行版,ZSH 似乎成了唯一能够在终端上聊以慰藉的工具,但是每每搭建新的虚拟机总是不可避免的重复如下步骤:

apt install -y zsh
apt install -y fonts-powerline

curl -O https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/install.sh
sed -i 's/-ohmyzsh\/ohmyzsh/-mirrors\/oh-my-zsh/g' install.sh
sed -i 's/-https:\/\/github.com\/${REPO}.git/-https:\/\/gitee.com\/${REPO}.git/g' install.sh
./install.sh

chsh -s $(which zsh) root
sed -i 's/ZSH_THEME="robbyrussell"/ZSH_THEME="ys"/g' ~/.zshrc
echo "alias ll='ls -alhF --time-style=long-iso'" >> ~/.zshrc

然而 ZSH 通过三两条命令搞定针对所有用户的默认配置,似乎并不是特别的容易。

后来慢慢摸索着发现搞定 Bash 默认配置实际上容易很多。比如 ubuntu 上 root 用户没有着色,可以直接拿模板用户去覆盖 root 用户:

cp /etc/skel/.bashrc ~/

再进一步甚至可以在/etc/bash.bashrcPS1相关配置之后添加源于/etc/skel/.bashrc的以下内容:

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
  # We have color support; assume it's compliant with Ecma-48
  # (ISO/IEC-6429). (Lack of such support is extremely rare, and such
  # a case would tend to support setf rather than setaf.)
  color_prompt=yes
    else
  color_prompt=
    fi
fi

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

再取消代码补全相关的注释,如此每个新用户即可直接:

# 直接删除
rm ~/.bashrc

# ubuntu 默认 /etc/profille 会去加载 /etc/bash.bashrc 而 centos 默认需要手动 source /etc/bashrc
source /etc/profile

然而 centos 中的PS1却没有可以直接 Ctrl+C、Ctrl+V 的来源,大概搜了下(https://www.cnblogs.com/iois/p/11665825.html)其中配色方案大致按照\[\e<A>;<B>;<F>m\]的顺序组合:

文本属性(A)背景颜色(B)文本颜色(F)
00:重置文本和背景40:黑色30:黑色
01:设置高亮度41:红色31:红色
04:下划线42:绿色32:绿色
05:闪烁43:黄色33:黄色
07:反显44:蓝色34:蓝色
08:消隐45:紫色35:紫色
46:青色36:青色
47:白色37:白色

于是就可以试试:

export PS1='[\[\e[01;05;32m\]\u\[\e[00m\]@\[\e[01;33m\]\h\[\e[00m\]:\[\e[01;34m\]\w\[\e[00m\]]\$ '

在这里插入图片描述
更改到 centos 的/etc/bashrc中即可永久生效。为了使得 centos 和 ubuntu 的行为一致,可以在/etc/profile中也去加载/etc/bashrc

cat >> /etc/profile << EOF
if [ -f /etc/bashrc ]; then 
    . /etc/bashrc
fi
EOF

source /etc/profile
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值