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

自 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.bashrc的PS1相关配置之后添加源于/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 its 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)}[33[01;32m]u@h[33[00m]:[33[01;34m]w[33[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
文本属性(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
经验分享 程序员 微信小程序 职场和发展