Display the git branch name at the prompt and follows branch switching

Change log
9sako6
9sako6
9sako6

The PROMPT_COMMAND variable is evaluated just before the prompt is displayed, so it is useful for dynamically displaying a branch name at the prompt.

In my .bashrc, I use PROMPT_COMMAND to display the branch name in the prompt as follows.

set_prompt() {
  PS1="\[\e]0;\u@\h: \w\a\]\[\033[01;32m\]\u\[\033[00m\]@\[\033[01;34m\]\w\[\033[00m\]($(git branch --show-current 2>/dev/null))\n$ "
}

PROMPT_COMMAND=set_prompt

You can display the current branch name following a branch switch with git switch or git checkout as follows.

example of the prompt

If PROMPT_COMMAND is not set, switching branches will leave the previous branch name at the prompt. Without PROMPT_COMMAND, we will have to do source ~/.bashrc manually or use git's post-checkout hook.

#References

  1. Bash Reference Manual
  2. What is the difference between PS1 and PROMPT_COMMAND?
    What is the difference between PS1 and PROMPT_COMMAND?
    While taking a look at this awesome thread I noticed that some examples use PS1="Blah Blah Blah" and some use PROMPT_COMMAND="Blah Blah Blah" (and some use both) when setting ...
    faviconstackoverflow.com