Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to checkout Git branches interactively

Working with Git, the one thing that you would do more often is to checkout branches. The way to checkout to a branch is by using the git checkout command.

So, if you want to checkout to a branch named develop, here’s how you can do it.

$ git checkout develop

This is fine but consider a scenario where you have got a lot of branches where the branch names are not that simple. In such a scenario, it’s pretty hard to checkout to branches. And that’s when this simple modification to the git checkout comes to the rescue which I learnt from this tweet.

Installing fzf fuzzy finder

Essentially, the idea is to make the command interactive so that, it’s easy to select the desired branch to checkout.

To do this, we can use a general-purpose fuzzy finder like fzf. It’s an interactive Unix filter for command-line that can be used with any list; files, command history, processes, hostnames, bookmarks, git commits, etc.

To get started, you would first need to install it. There is a bunch of instructions to install it on various platforms/OS. You can follow it along to install it.

For me, it was Ubuntu, so I used the apt-get install fzf command to install it on my system.

Customizing git checkout command

Next, we need to tweak the git checkout command to make it interactive using fzf like so.

$ git checkout (git branch -a | fzf | xargs)

Let’s break this down a bit.

The argument that we need to pass to the git checkout command is the name of the branch. So, passed the output of the git branch -a command (i.e. list of all the branches) to fzf.

The fzf fuzzy finder would then let you select the branch from that list interactively.

Now, when you select a branch using fzf, for some reason, there’s whitespace at the beginning of the branch name. To fix this, we can pass the selected branch name from fzf to xargs which will trim the branch name.

And that’s it. That’s how you can checkout branches interactively.

Here’s how this would look like in action.

Interactive git checkout using fzf

Making it seamless

The command we discuss isn’t practical to remember. To mitigate this, we can make a global Git alias for this command. So that, we can use it more seamlessly.

So, for instance, if we want to invoke the interactive checkout on git ci, here’s how we can set up a global Git alias for the same.

$ git config --global '!git checkout $(git branch -a | fzf | xargs)'

Here’s how this would look like in action.

Like this article? Consider leaving a


👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.