简体   繁体   中英

How Do I Display My Git Branch In My Terminal & Have It Automatically Update?

I am trying to have my terminal display my current/active working branch. Everything works as I intend besides the branch update, It is static. When I call ~/.bashrc or ~/.bash_profile it will update my active branch.

# 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).

Your mistake is here:

PS1+="\[${orange}\]$(git_branch) " # Call git_branch to be displayed.

Stuff inside double quotes is evaluated immediately, so ${orange} is expanded to whatever the variable orange expands to, and $(git_branch) is expanded to whatever git_branch produces on standard output.

There are many ways to solve this. One is to use single quotes, which prevent evaluation at this time. PS1 will thus contain a literal ${orange} and literal $(git_branch) . That will run the git_branch command at the right time, but depends on the variable $orange still being set at that time. Another is to replace $(git_branch) with \\$(git_branch) : when evaluated inside double quotes, the result is the literal text $(git_branch) , and when $PS1 is re-evaluated later, before each command, $(git_branch) gets its chance.

Note that the \\[...\\] parts of prompts are tricky. Bash internally changes these to $'\\001' and $'\\002' , and depending on where and when you evaluate parts of the prompt string, you may need to use the internal codes. This isn't really documented anywhere and relying on it might not be wise (but I did that in my own PS1 settings).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM