Can changes be made from one branch to another in Git?

2

I started using Git relatively recently and I have the bad habit of starting to program without creating a new branch. That is, I modify the code directly from the master branch.

Can the changes made in one branch be moved to another and thus leave the branch% co_of% clean?

    
asked by gmarsi 09.06.2017 в 12:53
source

2 answers

9

Yes, it is possible.

If you have not yet done any commit

Right now you are in master . If you type git status you will see a list of files that have been modified but not committed .

Simply create the branch:

git checkout -b nueva_rama

This command creates it and automatically takes you to it, taking all those changes with you.
Indeed, if you do git status again you will see that those changes appear there, so when doing a commit will be added to that branch nueva_rama , not% master .

If you have already done some commit

In this case, you must first undo it. As you read in How can I undo the last commit in Git? , use:

git reset HEAD~1

or more times if there are more commits. As of that moment, git status will show those changes again in the "uncommitted" state.

Then we are again in the previous point If you have not yet done any commit , so follow those steps.

You should also bear in mind that in master you will have a few commits to undo. Therefore, you must return to the previous state by doing git checkout <número del último commit válido> .

    
answered by 09.06.2017 / 12:56
source
3

If you have thrown a few commits in master what you have to do is simply create the branch with git checkout -b nueva_rama as the other answers say, if you have any change without commitear the commit eas or the stash eas, then you go back to your branch master with git checkout master , search with git log what is the commit to which the branch master should be, and change to master with git reset --hard commit_hash . You should have your new branch with the commits you wanted and your master branch behind it without the commits.

If you have not thrown any commits you just have to create the branch and commit your changes

If the branch already exists you can do a git rebase link and then stop at master and make a git reset --hard as in the first example

    
answered by 19.06.2017 в 17:04