Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to change to previously active branch?

I'm using git (in fact, msysgit) 1.6.4 on Windows. Most of the time I'm doing work in some feature branches. Every now and then, I want to hop back to master to cherry-pick one particular commit I did in my feature branch - usually because it's a useful bugfix which makes sense even without the feature. My workflow is like this - if this is unnecessarily complicated, please tell me :-) :

git checkout -b mycoolfeaturebranch
// hack away, implementing a feature and one bugfix (while I'm at it)

git add file_with_bugfix.cpp
git commit -m "Fixed bug 12345  // commit the bugfix
git checkout master             // hop over to master
git cherry-pick                 // bring the bugfix into master

At this point, I usually want to hop back to my feature branch to continue work on the feature. Unfortunately, my branch names tend to become a little long (like, 'mycoolfeaturebranch') and I don't have git branch name tab completion on Windows.

Is there maybe something like cd - on Unix shells (which hops to the previous directory, useful for toggling between two directories)? A git checkout - would be great. :-)

like image 656
Frerich Raabe Avatar asked Feb 28 '23 04:02

Frerich Raabe


2 Answers

From $GIT/Documentation/RelNotes-1.6.2.txt:

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

Did you try it?

like image 127
Stefan Näwe Avatar answered Mar 05 '23 14:03

Stefan Näwe


Try:

 git checkout @{-1}

From git rev-parse:

The special construct @{-<n>} means the th branch checked out before the current one.


As mentioned by Stefan Näwe in his answer:

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

Even though the syntax @{-1} has been around 1.6.2, it is only since 1.6.2 it is fully effective, as Junio C. Hamano comments back in February 2009 (emphasis mine):

The @{-1} syntax was added long before you started getting hyperactive this round, but it will be in 1.6.2 and has been advertised as "usable anywhere you can use a branch name", but in reality it is not.

I have been fixing up various places to match the reality with the claim.
I am making "git merge @{-1}" work now.


(Note: that differs from @{<n>}

A ref followed by the suffix @ with an ordinal specification enclosed in a brace pair (e.g. {1}, {15}) to specify the n-th prior value of that ref.
For example master@{1} is the immediate prior value of master while master@{5} is the 5th prior value of master.
This suffix may only be used immediately following a ref name and the ref must have an existing log ($GIT_DIR/logs/).

You can use the @ construct with an empty ref part to get at a reflog of the current branch.
For example, if you are on the branch blabla, then @{1} means the same as blabla@{1}.

)

like image 45
VonC Avatar answered Mar 05 '23 16:03

VonC