When working with Git on the command line, I spend a lot of time switching back and forth between two branches. Even with Git tab completion, it is a lot of typing. However Git has a shortcut for the previous branch, a single dash (-
).
Checkout Previous Branch
git checkout -
Example
While on the master
branch of your git project, you create a new branch and check it out.
git branch sf/fix-spacebar-overheat-1172
git checkout sf/fix-spacebar-overheat-1172
Now, you are on the new branch sf/fix-spacebar-overheat-1172
. The following line checks out your previous branch (master
).
git checkout -
If you git checkout -
again, you go back to sf/fix-spacebar-overheat-1172
.
Merge Previous Branch
I also like to use -
when merging.
git branch sf/fix-spacebar-overheat-1172
git checkout sf/fix-spacebar-overheat-1172
# add commits to sf/fix-spacebar-overheat-1172
git checkout -
git merge -
This example is tricky at first but a great workflow when you get the hang of it. Our two instances of -
in this example each refer to a different branch.
git branch sf/fix-spacebar-overheat-1172
git checkout sf/fix-spacebar-overheat-1172
# add commits to sf/fix-spacebar-overheat-1172
# switch to our previous branch (master)
git checkout -
# merge our previous branch (sf/fix-spacebar-overheat-1172)
git merge -
Deleting a Branch Does Not Work
The one thing this shortcut is missing is the ability to delete the previous branch. git branch -d -
does not work.
git branch -d -
error: branch '-' not found.
Any Previous Branch @{-n}
We can use a slightly longer version to refer our previous branch, which is @{-1}
.
# delete the previous branch
git branch -d @{-1}
Using the @{-n}
format can refer to other branches you previously checked out.
@{-1}
is the previous branch@{-2}
is the branch you had checked out before the previous branch@{-3}
is the branch you had checked out before before the previous branch- etc.
– is a shortcut
When we use -
, this is a special shortcut for @{-1}
Both of these will work but are more verbose than using -
git checkout @{-1}
git merge @{-1}
Introduced in Git 1.6.2
From the Git 1.6.2 release notes
@{-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.
Later in the release notes, they also call out
“git checkout -” is a shorthand for “git checkout @{-1}”.
Leave a Reply