使用PROMPT_COMMAND
以合理的方式建立價值。這節省了大量的引用,並使文本更具可讀性。請注意,您可以使用\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\]\[email protected]\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\\[email protected]\\h "
fi
PS1+="$blue\\w \\\$$reset "
}
這個問題似乎是脫離主題,因爲它是關於重構工作代碼。提名遷移到http://codereview.stackexchange.com/ – tripleee