Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Git Stashing and Shelving

Introduction

In this lesson, we will explore two important techniques in Git: Stashing and Shelving. These features allow developers to temporarily save changes that are not yet ready to be committed. This is particularly useful when you need to switch branches or work on a different task without losing your current progress.

Git Stashing

What is Git Stashing?

Git Stashing allows you to save your uncommitted changes in a stack-like structure. It effectively lets you "stash" your work and revert to a clean working directory.

Basic Commands

Note: Stashing is meant for temporary storage. Use it when you need to quickly switch tasks.
  1. Stash Changes:
    git stash

    This command will stash all your changes.

  2. List Stashes:
    git stash list

    View all stashed changes.

  3. Apply Stash:
    git stash apply

    Reapply the most recent stash.

  4. Drop Stash:
    git stash drop stash@{0}

    Remove a specific stash.

  5. Clear All Stashes:
    git stash clear

    Remove all stashed changes.

Example Scenario

Imagine you're working on a new feature and need to switch to the master branch to address a bug:

git stash
git checkout master
git pull
git checkout feature-branch
git stash apply

Git Shelving

What is Git Shelving?

Git Shelving is often considered a more advanced feature available in some Git GUIs. It allows you to store changes in a more organized way than stashing, often with more contextual information.

Common Commands

Tip: Use shelving when working on larger features that require context or when collaborating with others.
  1. Shelve Changes:
    git shelve

    Store your changes in the shelf.

  2. List Shelves:
    git shelf list

    View all shelved changes.

  3. Unshelve Changes:
    git unshelve

    Reapply the most recent shelved changes.

  4. Drop Shelf:
    git shelf drop

    Remove a specific shelf.

Best Practices

  • Always provide a descriptive message when stashing or shelving changes.
  • Use stashing for quick, temporary changes that you’ll return to soon.
  • Consider shelving for more complex changes that require context.
  • Regularly clean up your stash or shelf to avoid clutter.

FAQ

What happens to stashed changes if I switch branches?

Your stashed changes remain intact and can be reapplied on any branch.

Can I stash untracked files?

Yes, you can stash untracked files by using git stash -u.

What is the difference between stash and shelf?

Stash is for quick temporary storage, while shelf is more organized and contextual for larger changes.