我試圖讓我的終端顯示我當前/活動的作業分支。除了分支更新之外,一切都按我的意圖作業,它是靜態的。當我呼叫 ~/.bashrc 或 ~/.bash_profile 時,它??會更新我的活動分支。
# Pre-set colored text.
orange=$(tput setaf 166); # Orange Text Call
yellow=$(tput setaf 228); # Yellow Text Call
red=$(tput setaf 001); # Red Text Call
blue=$(tput setaf 004); # Blue Text Call
pink=$(tput setaf 005); # Pink Text Call
teal=$(tput setaf 006); # Teal Text Call
green=$(tput setaf 71); # Green Text Call
white=$(tput setaf 15); # White Text Call
bold=$(tput bold); # Bold Text Call
reset=$(tput sgr0); # Reset Call
# Display current git branch in terminal.
git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
PS1="\[${bold}\]\n"; # Display terminal text in BOLD & fresh line.
PS1 ="\[${blue}\] Branch:" # Display "Branch:" text.
PS1 ="\[${orange}\]$(git_branch) " # Call git_branch to be displayed.
PS1 ="\[${blue}\]User:" # Display "User:" text.
PS1 ="\[${orange}\]\u "; # Display active user.
PS1 ="\[${blue}\]Host:"; # Display "Host:" text.
PS1 ="\[${orange}\]\h "; # Display active host.
PS1 ="\[${blue}\]Directory:"; # Display "Directory:" text.
PS1 ="\[${orange}\]\W "; # Display working directory path.
PS1 ="\n"; # Create a new line to write on.
PS1 ="\[${white}\]-> \[${reset}\]"; # Display "$" & Color reset.
export PS1; # Export file to be used in terminal (source ~/.bashrc).
uj5u.com熱心網友回復:
你的錯誤在這里:
PS1 ="\[${orange}\]$(git_branch) " # Call git_branch to be displayed.
雙引號內的內容會立即計算,因此${orange}會擴展到變數orange擴展到的任何內容,并$(git_branch)擴展到git_branch標準輸出上產生的任何內容。
有很多方法可以解決這個問題。一種是使用單引號,這會阻止此時進行評估。PS1 因此將包含文字${orange}和文字$(git_branch)。這將git_branch在正確的時間運行命令,但取決于當時$orange仍在設定的變數。另一種方法是替換$(git_branch)為\$(git_branch): 在雙引號內計算時,結果是文字 text $(git_branch),并且 when$PS1稍后重新計算,在每個命令之前,$(git_branch)得到它的機會。
請注意,\[...\]提示的部分很棘手。Bash 在內部將這些更改為$'\001'and $'\002',并且根據您評估提示字串部分的位置和時間,您可能需要使用內部代碼。這在任何地方都沒有真正記錄下來,依賴它可能并不明智(但我在自己的 PS1 設定中這樣做了)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323985.html
標籤:猛击
上一篇:關于ls輸出和雙引號的簡單問題
