git stash apply: Save and Apply Changes when Needed

beginner
19 min

git stash apply: Save and Apply Changes when Needed

Welcome to our comprehensive guide on git stash apply! This tutorial is designed to help you understand how to save and apply changes when you need to switch branches but don't want to commit yet. Let's dive in! šŸŽÆ

What is git stash?

git stash is a Git command that helps you save your uncommitted changes. It's like a temporary storage for your work, allowing you to switch branches, work on something else, and later come back to your original work. šŸ’”

Why use git stash?

Sometimes, you might be in the middle of making changes and need to switch to another branch for some reason. But if you switch branches without saving your changes, they will be lost! That's where git stash comes in handy. It allows you to store your changes temporarily, switch branches, and apply them back later.

Stashing Changes

Before we dive into git stash apply, let's see how to stash our changes.

bash
$ git stash

This command will save your uncommitted changes and take you back to the last commit. You can see the stashed changes with:

bash
$ git stash list

Stash Apply

Now, let's move on to the main topic - git stash apply. After stashing your changes, you might want to apply them back to your current branch. Here's how:

bash
$ git stash apply

This command will apply the latest stashed changes to your current branch.

Stash Pop

If you want to both apply and delete the stashed changes, use git stash pop:

bash
$ git stash pop

Merge Conflicts

šŸ“ Note: If you have stashed changes on a branch that has been advanced, applying the stash might lead to merge conflicts if there are changes in the same files. In such cases, you'll need to resolve the conflicts manually before applying the stash.

Quiz

Quick Quiz
Question 1 of 1

What does `git stash` command do?

Practical Example

Let's see a practical example of using git stash and git stash apply.

  1. Start with a clean repository:
bash
$ git init $ touch readme.md $ git add readme.md $ git commit -m "Initial commit"
  1. Make some changes:
bash
$ echo "Updating readme" >> readme.md
  1. Stash the changes:
bash
$ git stash
  1. Check the stash:
bash
$ git stash list stash@{0}: WIP on master: Updating readme
  1. Switch to a different branch:
bash
$ git checkout new_branch
  1. Apply the stash:
bash
$ git checkout master $ git stash apply
  1. Verify the changes:
bash
$ cat readme.md Updating readme
  1. To delete the stash, use git stash drop:
bash
$ git stash drop

That's it! You've successfully used git stash apply to save and apply changes in Git. Happy coding! šŸŽ‰