In the local branch you do not want to commit the changes, but you need to switch to another branch

I am working on branch A and the function / task is not executing. Then I need to switch to another branch B for a quick fix. When I try to include another Git branch, it forces me to save my local changes, otherwise I will lose all local changes.

I need to pass my incomplete code. Is there a way that I can switch between multiple branches without committing or losing code? Or is there a better way to handle the situation?

+6
source share
2 answers

One option, as mipadi demonstrates , is to simply use git stash .

Another option is to simply simply do the current current job, switch branches, and then when you are ready to go back, do a mixed reset back to the previous commit:

 # While working on "feature" branch, # you suddenly need to go work on a hotfix: $ git commit --all --message "Backup my feature work" $ git checkout -b hotfix master # You did your hotfix, and are ready to go back to feature $ git checkout feature $ git reset head^ 

git reset head^ will perform a mixed reset back to commit before you commit the backup, and all the changes you make to the backup commit will be restored to your working copy. From the official Linux kernel documentation for git reset (highlighted by me):

Resets the index, but not the working tree (i.e., modified files are saved, but not marked for commit ) and reports that it was not updated. This is the default action.

+9
source

You can use git stash which will save your changes without creating a commit. 1

First save the changes:

 $ git stash 

Then switch to another branch:

 $ git checkout branch-B 

When you read, go back to your original branch and discard the changes:

 $ git checkout branch-A $ git stash pop 

See the documentation above for more details and details about additional use cases.


1 Technically, it creates a commit, but git stash uses some magic, so you don’t actually see a commit, and Git tools can handle these pseudo-statements correctly.

+8
source

Source: https://habr.com/ru/post/951090/


All Articles