Reputation: 9825
Sometimes when debugging I'll checkout commits from a branch. This puts me in detached head. Often I can use git checkout -
to go back to the branch head. But sometimes I'll checkout multiple commits in a row so this will just bring me back to the last commit. Is there a more surefire way to get back to the head of the branch? Is there a way without typing the whole branch name e.g. git checkout <branch-name>
?
Upvotes: 0
Views: 208
Reputation: 9825
Thanks for the other answer but I came up with another solution
git checkout `git branch --sort=committerdate | tail -1`
git branch --sort=comitterdate
will return branches in the order in which they were last checked out.
Heres what the output will look like when you are on a detached head, it doesnt keep track of history of detached branches so the first result will be the last non detached branch you were at.
branch1
branch2
master
* (HEAD detached at 1d4de8881)
last-non-detached-head-branch-checked-out
Upvotes: 0
Reputation: 14723
As an alternative to @Kaz's answer, you may want to give a try to git reflog
?
Then, git checkout HEAD@{1}
for example.
For more details, you can run man gitrevisions
or fetch the accompanying online doc. Excerpt:
[…]
<refname>@{<n>}, e.g. master@{1}
A ref followed by the suffix
@
with an ordinal specification enclosed in a brace pair (e.g.{1}
,{15}
) specifies the n-th prior value of that ref. For examplemaster@{1}
is the immediate prior value of master whilemaster@{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/<refname>
).
[…]
Upvotes: 0
Reputation: 58500
The sure-fire way to get back to the head of a branch is
git checkout <branch-name> # such as master
You may have to deal with any uncommitted changes first, and if you've made any commits in the detached state you will be warned that you're leaving them behind. You can cherry-pick
them into the branch, if they are valuable.
To create an alias for a branch name, you can use a variable in whatever shell you're using:
short="very-long-annoying-branch-name"
git co $short
git symbolic refs don't appear useful for this purpose. Another idea is to create git aliases for checking out specific branches.
Actual transcript:
$ git config --global alias.coms 'checkout master'
$ git coms
Already on 'master'
Your branch is ahead of 'remotes/origin/master' by 7 commits.
(use "git push" to publish your local commits)
Maybe avoid --global
for branch names very specific to particular repos.
Upvotes: 1