2014-03-12 42 views
8

所以我發現下面的陰涼Bash提示符:簡化先進的Bash提示符變量(PS1)代碼

Bash prompt

..with的非常基本的邏輯:

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\]\[email protected]\h'; fi)\[\033[01;34m\] \w \$\[\033[00m\] " 

然而,這不是非常基本的,碰巧是一個令人難以置信的混亂。我想讓它更具可讀性。

怎麼樣?

+0

這個問題似乎是脫離主題,因爲它是關於重構工作代碼。提名遷移到http://codereview.stackexchange.com/ – tripleee

回答

15

使用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 " 
} 
+0

+1優秀的答案。我只會進一步建議在函數內部使用'local'變量。 –

+0

好點。我會做出這樣的改變。 – chepner