DEV Community

Cover image for Determine the Git Branch You're On
Mohammad-Ali A'RÂBI
Mohammad-Ali A'RÂBI

Posted on • Originally published at Medium

Determine the Git Branch You're On

Branching is one of the most used features of git. People usually change branches all the time and need to determine which branch are they on, constantly.

Use Branch Command

The first git subcommand that deals with branches is the branch command. Just by writing this command down, a list of all your local branches and the branch you are on will be shown. Enter:

git branch
Enter fullscreen mode Exit fullscreen mode

And the output will be something like this:

  aerabi/add-readme
  aerabi/add-github-actions
* master
  the-hotfix-branch
Enter fullscreen mode Exit fullscreen mode

Your current branch is highlighted with an asterisk and a different color.

Use Status Command

The status command is a widely used powerful command that shows your current branch among other things. Enter:

git status
Enter fullscreen mode Exit fullscreen mode

And the output will be something like this:

On branch master 
Your branch is up to date with 'origin/master'. 

Changes not staged for commit: 
  (use "git add <file>..." to update what will be committed) 
  (use "git restore <file>..." to discard changes in working directory) 
        modified:   docker-compose.dev.yml 

Untracked files: 
  (use "git add <file>..." to include in what will be committed) 
        .idea/ 
        Dockerfile 
        docker-compose.override.yml.bak 

no changes added to commit (use "git add" and/or "git commit -a")
Enter fullscreen mode Exit fullscreen mode

The first line shows which branch are you on. The second shows your upstream branch if there are any set.

Use Your Bash Configurations

This part works for Bash on Debian-based Linux distributions like Ubuntu.

I am using bash on Ubuntu. When I’m on a directory, my bash will show me something like this:

mohammad@pc:~/Dev/my-git-project$ 
Enter fullscreen mode Exit fullscreen mode

So, all the time, I know which user account I’m using, on which host, and where on that host. It would be also very useful if your git branch would show up additionally. For it to happen, open your .bashrc file using your editor of choice:

vim ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

And add the following line to the end of the file:

PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\[\e[91m\]\$(__git_ps1 ' [%s]')\[\e[00m\]\$ "
Enter fullscreen mode Exit fullscreen mode

Save and exit. Now, open a new terminal (or type source ~/.bashrc) and the git branch will show up whenever you’re in a git repository:

mohammad@pc:~/Dev/my-git-project [master]$
Enter fullscreen mode Exit fullscreen mode

Conclusion

Try to configure your shell to show the git branch, it saves you a lot of time.

This article was originally published on Medium. I write weekly on git and monthly on Docker:

Top comments (0)