Beautify bash

Beautify bash

Considering zsh is not very friendly to machines with weak performance, I referred to the methods of online experts to beautify bash.

Configure ble.sh

GitHub link

Here is the official installation guide:

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

Afterwards, use source ~/.bashrc to check the effect:

image-20250222133949356

It uses the same autosuggestions logic as zsh, using the -> key to complete historical commands.

Configure bash appearance

Referring to an expert’s article, a Fish-like path folding was implemented, and the result of the last command execution is judged by the username color.

Create file 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> '
}

Then, at the end of .bashrc, source the my_bash.sh file:

Result:

image-20250222134037919

When there is an error status:

image-20250222134053613

Reference articles:

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

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