Git: set branch to current ref

Git

Git Problem Overview


Due to the use of submodules in my projects I'm finding myself often on "(no branch)". As I'm also adding code to those submodules I'm committing in there. When I then want to push those submodules I need to be on a branch of course. Hence my question:

Is there a way/shortcut in git (command line) to set a local branch to the current commit/HEAD without the detour of

git checkout the_branch
git reset --hard <previous commit-ish>

To be more precise, my real problem with the above "detour" is that I'm temporarily leaving the original HEAD with the checkout-command. That can be avoid with the git branch -f command (thanks to CharlesB).

Git Solutions


Solution 1 - Git

Checkout the branch with -B: this will reset the branch to HEAD, which is the current ref.

git checkout -B <branch> 

From the docs:

> If -B is given, is created if it doesn’t exist; > otherwise, it is reset. This is the transactional equivalent of > > $ git branch -f [] > $ git checkout > > that is to say, the branch is not reset/created unless "git > checkout" is successful.

Solution 2 - Git

git checkout -B the_branch HEAD

This will checkout the_branch at commit HEAD, even if the_branch pointed somewhere else before. It was added in one of the last few git releases, so you might not have it available. An alternate route would be git branch -D the_branch && git checkout -b the_branch

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrick B.View Question on Stackoverflow
Solution 1 - GitCharlesBView Answer on Stackoverflow
Solution 2 - GitknittlView Answer on Stackoverflow