Mastering Git Stash: A Developer's Best Friend

Mastering Git Stash: A Developer's Best Friend

 

When working on a feature branch, you've likely encountered moments when you need to switch contexts. Perhaps a bug in the main branch requires immediate attention, but you’re in the middle of an uncommitted, incomplete feature. In such cases, Git stash can be a lifesaver. This command temporarily shelves your changes, allowing you to switch branches without committing half-baked work.

 

What is Git Stash?

Git stash is a Git command that lets you save your uncommitted changes temporarily without committing them to the repository. It's like placing your work on a clipboard while you attend to something else. Once you're ready, you can restore those changes and resume where you left off.

 

Common Use Cases for Git Stash

Switching branches: If you're in the middle of changes and need to switch to another branch, Git stash prevents conflicts by storing your changes

  • temporarily.
  • Testing or experimenting: Use Git stash to save your current progress before testing or experimenting with other changes.

    Pulling updates: Stash changes before pulling updates from the remote repository to ensure your local work isn't overwritten.

 

Basic Git Stash Commands

 

Stash Your Changes

Run the following command to save your uncommitted changes:

git stash

or 

git stash save -m “your message”

or 

git push -m “your message”

Stash uncommited file as well 

you can -u option

git stash save -u -m “your message”

 

View Stash List

To see a list of all stashes, use:

git stash list

Each stash is assigned a name like stash@{0} for reference.

 

Apply Stashed Changes

To restore the most recent stash, use

git stash apply

This will apply latest stash

If you want to apply a specific stash from the list:

git stash apply stash@{n}  # n stash refrence no
git stash apply stash@{1}

or 

git stash apply n  # stash refrence no
git stash apply 1

 

Remove Stash

git stash drop stash@{n}

Or clear all stashes at once:

git stash clear

 

Pop a Stash

To apply and immediately remove the stash:

Pop Stash and apply latest one

git stash pop

Specific stash pop and apply

git stash pop stash@{n}

 

Create a Branch from a Stash

To create a branch directly from a stash:

To create branch with latest stash

git stash branch <branch-name>

To create branch with specific stash

git stash branch <branch-name> stash@{n}

 

To Show changes inside stash

To show changes inside without apply it

git stash show -p stash@{n}  // -p view

To show only files

git stash show stash@{n}

To show changes in specific file

git stash show -p stash@{n} – file_path

Related Posts
Mastering Git Configuration Essential Settings for Every Developer
Mastering Git Configuration Essential Settings for Every Developer

Git is an indispensable tool for developers, enabling version control and collaboration on projects ...

Git