Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to git checkout previous branch?

I sort of want the equivalent of cd - for git. If I am in branch master and I checkout foo, I would love to be able to type something like git checkout - to go back to master, and be able to type it again to return to foo.

Does anything like this exist? Would it be hard to implement?

like image 564
Matt Briggs Avatar asked Aug 26 '11 15:08

Matt Briggs


People also ask

Can I checkout a previous commit?

To pull up a list of your commits and their associated hashes, you can run the git log command. To checkout a previous commit, you will use the Git checkout command followed by the commit hash you retrieved from your Git log.

Can we revert git checkout?

Git Checkout FileIf you stage and commit the checked-out file, this has the effect of “reverting” to the old version of that file. Note that this removes all of the subsequent changes to the file, whereas the git revert command undoes only the changes introduced by the specified commit.


2 Answers

From the release notes for 1.6.2

@{-1} is a way to refer to the last branch you were on. This is
accepted not only where an object name is expected, but anywhere a branch name is expected and acts as if you typed the branch name.
E.g. git branch --track mybranch @{-1}, git merge @{-1}, and
git rev-parse --symbolic-full-name @{-1} would work as expected.

and

git checkout - is a shorthand for git checkout @{-1}.

like image 111
Karl Bielefeldt Avatar answered Sep 17 '22 13:09

Karl Bielefeldt


The simplest way of doing this nowadays is:

git checkout - 

... which is an alias of:

git checkout @{-1} 

git checkout minus

If you want to know more about this, I wrote an entire article about it here: Checkout The Previous Branch In Git.

like image 31
marcgg Avatar answered Sep 20 '22 13:09

marcgg