How to Improve Your Git Checkout Process
August 01, 2020
TL;DR
You will need FZF, git, and a linux/unix-based operating system to follow along. The same workflow is probably possible on Windows, but I don’t know how to do it.
Here is the command, I recommend setting up an alias for it:
git branch | fzf | xargs git checkout
My previous workflow
If you are like me, you work on projects with a ton of git branches. I work on one project which has 87 branches at the moment, and another with 36.
When I need to switch branches, I can never remember what the name of the branch I am looking for is. Today, I started thinking about how I could fix that, besides jumping into a GUI application to see an easier-to-work-with list.
Improving the workflow
One of my favorite command line tools is FZF. FZF is a tool which allows you to pipe text into it, then filter it.
I started out playing with my idea in the most simple form:
git branch | fzf
This presents an interface like this:
* mainbranch-6branch-5branch-4branch-3branch-2branch-17/7> |
The caret at the bottom is where you can type in your filter. As you type, the list will get shorter. Eventually, you select the option you are looking for.
The selected item is printed to stdout:
$ git branch | fzfbranch-1
Now that I knew how to get the item I wanted, I needed to use it in an
execution of git checkout
. I tried this:
git branch | fzf | git checkout
Unfortunately, git checkout
does not seem to accept its argument from the
standard input stream. This sent me on a web search, where I found
xargs
.
I have seen xargs in the past, but never taken a few minutes to familiarize myself with it. As it turns out, xargs was exactly what I needed.
xargs takes content from the standard input stream, and uses that content as string argument(s) for the execution of whatever utility you pass to it. Here is an example using it:
$ echo "Hello," "world"Hello, world$ echo "Hello, world" | xargs echoHello, world$ echo "world" | xargs echo "Hello,"Hello, world
First, I show that echo
can accept many string arguments, which get
concatenated with a space character. Next, I show an example of using xargs
to pass the only argument to echo
. Finally, I show that we can even pass
arguments directly to the executed utility, and use xargs to append
stdout as more arguments.
Here is how it looks to apply this to our git checkout
execution:
git branch | fzf | xargs git checkout
Using this line, git checkout
will be given whatever I choose in fzf as
an argument. If I choose branch-1
, the execution is the same as typing
git checkout branch-1
manually.
This was exactly what I was looking for, and here is what it looks like in action:
$ git branch | fzf | xargs git checkoutSwitched to branch 'branch-1'
Thank You, Friend
Thanks for stopping by, I really hope this helped you!