git stash 🎯

beginner
16 min

git stash 🎯

Welcome to our comprehensive guide on using git stash! In this tutorial, we'll learn how to manage changes in your working directory, even when you can't commit them right away. Let's dive in!

What is git stash? 📝

git stash is a useful command that helps you save your current changes temporarily, so you can switch to another branch or task without losing your work. It's like a 'to-do list' for your git work!

Why use git stash? 💡

Imagine you're working on a feature branch, but suddenly you're asked to fix an urgent bug on the master branch. Without git stash, you'd have to either abandon your feature work or commit it unfinished. But with git stash, you can save your changes, switch to the master branch, fix the bug, and then return to your feature work later.

Basic git stash commands 🎯

git stash save

This command saves your current changes, including both staged and unstaged ones.

bash
$ git stash save "My work in progress"

git stash list

This command shows you a list of your stashed changes. Each stash is given a unique ID.

bash
$ git stash list stash@{0}: My work in progress on feature-branch

git stash apply

This command applies the latest stashed change to your working directory.

bash
$ git stash apply

git stash drop

This command removes the latest stashed change from the list.

bash
$ git stash drop

Practical Example 💡

Let's see git stash in action with a simple project.

  1. Create a new repository and navigate into it:
bash
$ mkdir my-project $ cd my-project $ git init
  1. Create a new file and make some changes:
bash
$ touch index.html $ echo "Hello, World!" > index.html
  1. Stage and commit the changes:
bash
$ git add index.html $ git commit -m "Initial commit"
  1. Create a new branch and make more changes:
bash
$ git checkout -b feature-branch $ echo "This is a feature!" >> index.html
  1. Save the changes as a stash:
bash
$ git stash save "Feature changes"
  1. Switch to the master branch and make a commit:
bash
$ git checkout master $ echo "Fixed an urgent bug!" >> index.html $ git commit -am "Fix urgent bug"
  1. Apply the stashed changes back to the working directory:
bash
$ git checkout feature-branch $ git stash apply

Now, your feature changes are back in your working directory!

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What command saves your current changes in git?

Quick Quiz
Question 1 of 1

What command shows a list of your stashed changes in git?

Quick Quiz
Question 1 of 1

What command applies the latest stashed change to your working directory in git?

Keep learning and happy coding! 💡