I've only recently started using Git and I have a bad habit of starting programming without first creating a new branch. That is, I modify the code directly from the branch master
.
Can changes made in one branch be moved to another and thus leave the branch master
clean?
If possible.
If you haven't done any yet
commit
Right now you are in
master
. If you type yougit status
will see a list of files that have been modified but not committed .Just create the branch:
This command creates it and automatically takes you to it, taking all those changes with it.
Indeed, if you do it
git status
again you will see those changes appear there, so doing acommit
will push them to that branchnueva_rama
, not tomaster
.If you have already done
commit
In this case, it will have to be undone first. As read in How can I undo the last commit in Git? , uses:
or more times if there are more commits. From that moment on,
git status
it will show those changes again in "uncommitted" status.So we are back to the previous point If you haven't done any yet
commit
, so follow those steps.You should also keep in mind that
master
you will have quite a few commits to undo. Therefore, you must return to the previous state by doinggit checkout <número del último commit válido>
.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 committing itcommit
,stash
then you return to your branchmaster
withgit checkout master
, they look forgit log
which one it is with commit to which the branchmaster
should be, and you switch to master withgit reset --hard commit_hash
. You should be left with your new branch with the commits you wanted and your master branch behind it without the commits.If you haven't pulled any commits you just have to create the branch and commit your changes
If the branch already exists you can do a
git rebase
https://git-scm.com/docs/git-rebase and then stop at master and do agit reset --hard
like in the first example