Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Git branch with current changes

Tags:

git

git-branch

I started working on my master branch thinking that my task would be easy. After a while I realized it would take more work and I want to do all this work in a new branch.

How can I create a new branch and take all these changes with me without dirtying master?

like image 448
willcodejavaforfood Avatar asked Oct 10 '10 08:10

willcodejavaforfood


People also ask

Can I create a branch with current changes?

You can do a checkout and create a new branch with all local and current changes transferred over.

How do I create a new branch and keep changes?

The git checkout -b <BranchName> command will create a new branch and switch to it. Moreover, this command will leave the current branch as it is and bring all uncommitted changes to the new branch.

Does git checkout create new branch from current branch?

New Branches Git checkout works hand-in-hand with git branch . The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.


1 Answers

If you hadn't made any commit yet, only (1: branch) and (3: checkout) would be enough.
Or, in one command: git checkout -b newBranch

With Git 2.23+ (Q3 2019), the new command git switch would create the branch in one line (with the same kind of reset --hard, so beware of its effect):

# First, save your work in progress! git stash  # Then, one command to create *and* switch to a new branch git switch -f -c topic/wip HEAD~3 

As mentioned in the git reset man page:

$ git stash                # (0) Save your work in progress $ git branch topic/wip     # (1) $ git reset --hard HEAD~3  # (2)  NOTE: use $git reset --soft HEAD~3 (explanation below) $ git checkout topic/wip   # (3) 
  1. You have made some commits, but realize they were premature to be in the "master" branch. You want to continue polishing them in a topic branch, so create "topic/wip" branch off of the current HEAD.
  2. Rewind the master branch to get rid of those three commits.
  3. Switch to "topic/wip" branch and keep working.

Again: new way (since 2019 and Git2.23) to do all that in one command:

git switch -f -c topic/wip HEAD~3 

Note: due to the "destructive" effect of a git reset --hard command (it does resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded), I would rather go with:

$ git reset --soft HEAD~3  # (2) 

This would make sure I'm not losing any private file (not added to the index).
The --soft option won't touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do).


like image 111
VonC Avatar answered Nov 18 '22 01:11

VonC