Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: set branch to current ref

Tags:

git

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).

like image 836
Patrick B. Avatar asked Sep 28 '11 08:09

Patrick B.


People also ask

How do I force a branch to update?

Use git push -f to force update the remote branch, overwriting it using the local branch's changes.

How do I change a branch to a previous commit?

Make sure you are on the branch to which you have been committing. Use git log to check how many commits you want to roll back. Then undo the commits with git reset HEAD~N where “N” is the number of commits you want to undo. Then create a new branch and check it out in one go and add and commit your changes again.

How do I set up a Upstream branch?

The easiest way to set the upstream branch is to use the “git push” command with the “-u” option for upstream branch. Alternatively, you can use the “–set-upstream” option that is equivalent to the “-u” option. As an example, let's say that you created a branch named “branch” using the checkout command.


1 Answers

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 <branch> [<start point>] $ git checkout <branch> 

that is to say, the branch is not reset/created unless "git checkout" is successful.

like image 154
CharlesB Avatar answered Sep 20 '22 00:09

CharlesB