bash美化

bash美化

感觉zsh着实对性能羸弱的机子不太友好,参考网上大佬的方式,进行下bash的美化。

配置ble.sh

github链接

这里搬运下官方安装教程:

1
2
3
git clone --recursive --depth 1 --shallow-submodules https://github.com/akinomyoga/ble.sh.git
make -C ble.sh install PREFIX=~/.local
echo 'source ~/.local/share/blesh/ble.sh' >> ~/.bashrc

之后使用source ~/.bashrc查看效果:

image-20250222133949356

与zsh的autosuggestions逻辑一致,使用->键补全历史命令。

配置bash外观

参考大佬的文章,做了仿Fish的路径折叠,并且通过用户名颜色判断上一命令执行结果。

创建文件my_bash.sh:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function _fish_collapsed_pwd() {
local pwd="$1"
local home="$HOME"
local size=${#home}
[[ $# == 0 ]] && pwd="$PWD"
[[ -z "$pwd" ]] && return
if [[ "$pwd" == "/" ]]; then
echo "/"
return
elif [[ "$pwd" == "$home" ]]; then
echo "~"
return
fi
[[ "$pwd" == "$home/"* ]] && pwd="~${pwd:$size}"
if [[ -n "$BASH_VERSION" ]]; then
local IFS="/"
local elements=($pwd)
local length=${#elements[@]}
for ((i=0;i<length-1;i++)); do
local elem=${elements[$i]}
if [[ ${#elem} -gt 1 ]]; then
elements[$i]=${elem:0:1}
fi
done
else
local elements=("${(s:/:)pwd}")
local length=${#elements}
for i in {1..$((length-1))}; do
local elem=${elements[$i]}
if [[ ${#elem} > 1 ]]; then
elements[$i]=${elem[1]}
fi
done
fi
local IFS="/"
echo "${elements[*]}"
}

PROMPT_COMMAND=__prompt_command # Function to generate PS1 after CMDs

__prompt_command() {
local EXIT="$?" # This needs to be first
PS1=""

local RCol='\[\e[0m\]'

local Red='\[\e[0;31m\]'
local Gre='\[\e[0;32m\]'
local BYel='\[\e[1;33m\]'
local BBlu='\[\e[1;34m\]'
local Pur='\[\e[0;35m\]'
if [ $EXIT != 0 ]; then
PS1+="${Red}\u${RCol}" # Add red if exit code non 0
else
PS1+="${Gre}\u${RCol}"
fi

PS1+="${RCol}@${BBlu}\h ${Pur}$(_fish_collapsed_pwd)${RCol} "
export PROMPT='%F{135}%n%f@%F{166}%m%f %F{2}$(_fish_collapsed_pwd)%f> '
}

然后在bashrc末尾source

效果:

image-20250222134037919

状态错误时:

image-20250222134053613

参考文章:

你不需要花哨的命令提示符 - 知乎 (zhihu.com)

linux - Bash prompt with the last exit code - Stack Overflow