Git父分支意外获取子分支代码,如何阻止该情况?
Hey there, let's break down why this is happening and get it sorted for you.
First, let's clear up a key point: Git doesn't "automatically sync" child branches to parent branches on its own. The issue here is that your changes on branch2 were uncommitted (either unstaged, or staged but not yet saved to a commit). Git preserves your local uncommitted work when switching branches to avoid losing edits, which is why those changes showed up on branch1.
Step 1: Secure Your Changes on branch2
First, switch back to branch2 to properly lock in your work:
- If you haven't staged your changes yet, stage them with:
(Replacegit add ..with specific filenames if you don't want to stage every modified file.) - Commit the changes to
branch2to save them to this branch's history:git commit -m "Add [brief description of your changes here]"
Now your edits are safely stored in branch2 and won't follow you when switching branches.
Step 2: Clean Up Unwanted Changes on branch1
If you're already on branch1 and see those unintended changes, you can revert branch1 to its clean state:
- First confirm the uncommitted changes with:
git status - To discard all uncommitted changes on
branch1(note: this will permanently delete unsaved work here, so double-check you don't need it):
(Use specific filenames instead ofgit checkout -- ..if you only want to discard certain files.)
Step 3: Best Practices to Avoid This in the Future
To keep your branches isolated until you're ready to merge, follow these habits:
- Always commit your changes to the current branch before switching to another branch.
- If you're not ready to commit yet, stash your changes temporarily:
This saves your edits in a hidden "stash" that won't interfere with other branches. When you return togit stashbranch2, restore the stash with:git stash pop - Once your
branch2code is fully verified, switch tobranch1and merge intentionally:git checkout branch1 git merge branch2
内容的提问来源于stack exchange,提问作者Sagar

