Master Git & GitHub From Scratch

Clear, practical, and structured lessons designed to take you from Git fundamentals to real-world GitHub collaboration.

Switching Context

When you need to switch branches but aren't ready to commit your current work, Git provides two primary ways to handle your context: stashing your changes or carrying them with you.

Here is how to manage your context depending on what you want to do with your uncommitted changes.


Option 1: Hide Your Work Safely (Git Stash)

If your current work is incomplete and you want a clean slate before switching branches, use the stash. This saves your changes temporarily and cleans the affected tracked files in your working directory.

1. Save Your Changes
git stash

Saves changes to tracked files and clears those changes from your working directory.

2. Switch to Another Branch
git switch <other-branch>

Switches to your target branch.

3. Return to Your Original Branch
git switch <original-branch>

Switches back to the branch where you saved your work.

4. Restore Your Changes
git stash pop

Restores the most recent stash and removes it from the stash list if it applies successfully.

Tip: Use git stash -u if you also need to stash untracked files.

Option 2: Bring Your Changes With You

If you accidentally started working on the wrong branch, you may be able to switch branches while keeping your current uncommitted changes.

1. Switch to an Existing Branch
git switch <existing-branch>

Moves to the specified branch while carrying compatible uncommitted changes in your working directory.

2. Create a New Branch and Switch
git switch -c <new-branch>

Creates a new branch and immediately switches to it, keeping compatible uncommitted changes.

Note: Git may block the switch if your changes would be overwritten by files on the destination branch. In that case, commit or stash your changes before switching.

Option 3: Discard Changes (Hard Reset)

If you no longer need your uncommitted changes, you can discard changes to tracked files before switching branches.

git reset --hard HEAD
Warning: This permanently discards uncommitted changes to tracked files in your working directory and index. The operation may be difficult or impossible to undo. Make sure you do not need those changes before running it.

Quick Reference

Command Purpose
git stash Temporarily save changes to tracked files
git stash -u Stash tracked and untracked files
git stash pop Restore and remove the latest stash when applied successfully
git switch <branch> Switch branches while preserving compatible changes
git switch -c <branch> Create a branch and switch to it
git reset --hard HEAD Discard uncommitted changes to tracked files
Key Takeaway: Use git stash when you want to save unfinished work temporarily. Switch branches directly when Git can safely carry your changes. Use git reset --hard HEAD only when you intentionally want to discard tracked-file changes.