Last Updated: February 25, 2016
·
1.245K
· christopherhein

Checkout last branch without writing the name.

In my job I usually find myself switching branches back and forth very often. This is sometime difficult to remember the last working tree you were on if you've already gone through a lot of changes.

So I setup two alias to use for checkouts.

[alias]
  co = "!git rev-parse --abbrev-ref HEAD > .last_branch ; git checkout"
  coo = "!git co `cat .last_branch`"

When checking out a branch git co -b new-branch it creates a new file in the root of your project called .last_branch with just the current working tree before the checkout, then will checkout the branch allowing you to work as normal.

When you want to checkout the last branch just use git coo and it'll cat the .last_branch file and checkout the original branch.

Very helpful when you find yourself working on many peoples branches very frequently.

Now you most likely are going to want to add .last_branch to your .gitignore

2 Responses
Add your response

you can also merge with -,
so can you do something like

> git checkout -b new_feature
// do stuff
> git commit -am "done"
> git checkout master
> git merge -
over 1 year ago ·

You can get a reference to the last branch by using -.

$ git checkout master # => master
$ git checkout -b new-branch # => new-branch
$ git checkout - # => master
$ git checkout - # => new-branch
$ git merge - # => merges master into new-branch
over 1 year ago ·