I added a new branch to my git repository for a new feature I was adding and forgot to explicitly check it out. I have since changed a lot of files without committing, but I want to be able to commit these changes to the alternate branch, not the master. How can I do this safely?
when you switch to a branch without committing changes in the old branch, git tries to merge the changes to the files in the new branch. If merging is done without any conflict, swithing branches will be successful and you can see the changes in the new branch.
Use the git switch - (Or git checkout - ) to switch to the previous branch you were working with. This is pretty similar to the cd - command, which is used to switch to the previous directory.
Checking out branches Checking out a branch updates the files in the working directory to match the version stored in that branch, and it tells Git to record all new commits on that branch. Think of it as a way to select which line of development you're working on.
Using the git checkout Command 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. There is no local change on the master branch, as we can see in the output.
You can just checkout the new branch - your uncommitted changes will be carried over to the new branch. (This isn't allowed if your local changes would affect a file that would be changed by switching branch, but in this case it sounds as if the new branch is at the same position as your last commit, so that won't be a problem.)
git stash
git checkout other_branch
git stash pop
Ought to do the trick. You can then commit as normal. See also: git stash manual page
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With