Show Git Branch In Terminal – Command Prompt

When you are working inside a Git repository it is important to realize what is the currently checked out Git branch.

You can make it easier to track where you are, by showing the name of the current Git branch in the terminal (command prompt).

In the almost any Linux distribution, including Ubuntu and CentOS, this can be easily done by configuring a primary prompt string, that is controlled via a special shell variable PS1

Cool Tip: Have forgotten the meaning of some term in Git? Not a problem! Simply read and bookmark this article! This article →

Show Git Branch In Terminal

To display the current prompt setting, run:

$ echo $PS1

Sample output:

[\u@\h \W]$

Open the ~/.bashrc file with your favorite text editor and add the following lines:

git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

export PS1="[\u@\h \W]\$(git_branch)\$ "

The git_branch() is a function, that prints the name of the current Git branch in the round brackets.

We set the PS1 variable and place the function git_branch() inside it to display the Git branch in the terminal prompt.

The function inside the PS1 variable must be in the following format: \$(git_branch).

Load the ~/.bashrc to apply changes for the current session without login/logout:

$ source ~/.bashrc

From now, as only you enter a directory that is tracked by Git, you will see the current Git branch name in the terminal prompt:

[user@host ~]$ cd project/
[user@host project](master)$ git branch
* master

To prettify your command prompt you can colorize a Git branch name by wrapping \$(git_branch) into ANSI escape codes, like \033[00;32m\]\$(git_branch)\[\033[00m\] (green foreground color, normal characters):

export PS1="[\u@\h \W]\[\033[00;32m\]\$(git_branch)\[\033[00m\]\$ "

Cool Tip: Choose the best COLORS and styles for your terminal prompt! Read more →

The terminal prompt looks quite pretty now:

[user@host ~]$ cd project/
[user@host project](master)$ git branch
* master

2 Replies to “Show Git Branch In Terminal – Command Prompt”

  1. zsh с дополнением https://github.com/robbyrussell/oh-my-zsh/ (Oh-My-Zsh) подойдёт ещё лучше 😉

  2. HI Sorry to ask you this basic question. I don’t understand the line below
    Open the ~/.bashrc file with your favorite text editor and add the following lines:
    How do you do that? Could you possibly tell me exactly what to do?

Leave a Reply