Switching Branches in Git Without Losing Code: Using Stash to Temporarily Store Uncommitted Changes

### Guide to Using Git Stash for Temporarily Stashing Changes When developing with Git, uncommitted modifications will be overwritten if you switch branches. Git Stash is a temporary storage tool that can save uncommitted changes in both the working directory and staging area, restoring a clean working directory for safe branch switching. **Core Operations**: 1. **Stash Changes**: Run `git stash` to temporarily save all uncommitted changes and clear the working directory (outputs a WIP record like "Saved working directory..."). 2. **Switch Branches**: Use `git checkout <target-branch>` to safely switch branches and focus on tasks. 3. **Restore Changes**: After completing work, switch back to the original branch and use `git stash pop` to restore stashed changes (removes the record); use `git stash apply` if you need to keep the record. **Additional Commands**: - `git stash list` to view all stashed records; - `git stash drop stash@{n}` to delete a specific record (where `n` is the index). **Conflict Handling**: If conflicts occur during restoration, manually resolve conflicted files (marked with `<<<<<<< HEAD` at the start), then execute `git add <conflict-file>` (Note: The original text may have been truncated here; the command should be completed as `git add <conflict-file>` followed by commit/resolution steps).

Read More
Git Version Rollback: How to Undo an Incorrect Commit and Retrieve Code

Git version rollback requires scenario-specific handling to avoid sensitive information leaks or code loss. For un-pushed incorrect commits, use `git reset`: `--soft` retains modifications and only undoes the commit, allowing re-submission of correct content; `--hard` completely discards modifications (irreversible, use with caution). For pushed incorrect commits, use `git revert` to create a new undo commit (safe for collaboration), e.g., `git revert HEAD` or specify a hash value. If code is accidentally deleted, use `git reflog` to view operation history, find the target commit hash, then restore with `git reset --hard <hash>`. Note: Prefer `--soft` for un-pushed commits, always use `revert` for pushed commits, avoid `--hard` in multi-person collaboration, and confirm the commit hash before operations.

Read More