简化高级Bash提示变量(PS1)代码
因此,我发现了以下很酷的Bash提示符: …基本逻辑如下:简化高级Bash提示变量(PS1)代码,bash,ps1,Bash,Ps1,因此,我发现了以下很酷的Bash提示符: …基本逻辑如下: PS1="\[\033[01;37m\]\$? \$(if [[ \$? == 0 ]]; then echo \"\[\033[01;32m\]\342\234\223\"; else echo \"\[\033[01;31m\]\342\234\227\"; fi) $(if [[ ${EUID} == 0 ]]; then echo '\[\033[01;31m\]\h'; else echo '\[\033[01;32m\]\
PS1="\[\033[01;37m\]\$? \$(if [[ \$? == 0 ]]; then echo \"\[\033[01;32m\]\342\234\223\"; else echo \"\[\033[01;31m\]\342\234\227\"; fi) $(if [[ ${EUID} == 0 ]]; then echo '\[\033[01;31m\]\h'; else echo '\[\033[01;32m\]\u@\h'; fi)\[\033[01;34m\] \w \$\[\033[00m\] "
然而,这不是很基本,而且碰巧是一个令人难以置信的混乱。我想让它更具可读性
如何?使用
提示符\u命令
以合理的方式建立价值。这节省了大量引用,使文本更具可读性。请注意,可以使用\e
而不是\033
来表示提示符中的转义字符
set_prompt () {
local last_command=$? # Must come first!
PS1=""
# Add a bright white exit status for the last command
PS1+='\[\e[01;37m\]$? '
# If it was successful, print a green check mark. Otherwise, print
# a red X.
if [[ $last_command == 0 ]]; then
PS1+='\[\e[01;32m\]\342\234\223 '
else
PS1+='\[\e[01;31m\]\342\234\227 '
fi
# If root, just print the host in red. Otherwise, print the current user
# and host in green.
# in
if [[ $EUID == 0 ]]; then
PS1+='\[\e[01;31m\]\h '
else
PS1+='\[\e[01;32m\]\u@\h '
fi
# Print the working directory and prompt marker in blue, and reset
# the text color to the default.
PS1+='\[\e[01;34m\] \w \$\[\e[00m\] '
}
PROMPT_COMMAND='set_prompt'
您可以为更深奥的转义序列定义变量,代价是需要在双引号内进行一些额外的转义,以适应参数扩展
set_prompt () {
local last_command=$? # Must come first!
PS1=""
local blue='\[\e[01;34m\]'
local white='\[\e[01;37m\]'
local red='\[\e[01;31m\]'
local green='\[\e[01;32m\]'
local reset='\[\e[00m\]'
local fancyX='\342\234\227'
local checkmark='\342\234\223'
PS1+="$white\$? "
if [[ $last_command == 0 ]]; then
PS1+="$green$checkmark "
else
PS1+="$red$fancyX "
fi
if [[ $EUID == 0 ]]; then
PS1+="$red\\h "
else
PS1+="$green\\u@\\h "
fi
PS1+="$blue\\w \\\$$reset "
}
这个问题似乎离题了,因为它是关于重构工作代码的。提名迁移到+1非常好的答案。我只是进一步建议在函数中使用
local
变量。