git stash explained in detail with examples | GoLinuxCloud (2023)

Table of contents

Notice

What is Git Stash?

  • The git stash command saves a copy of your uncommitted changes in a queue next to your project.
  • By uncommitted changes I mean items in the staging area or working directory that have been modified but not committed to the local repository.
  • Each time the stash command is invoked and there is uncommitted content (since the last stash command), Git creates a new item in the queue to store that content. This content can reside in the staging area, the working directory, or both.
  • After creating the stash and storing the uncommitted content, Git basically does the following:git reset --hardheadOperation. However, since you have the stash, no uncommitted changes are lost.

Git Stash-Syntax

The syntax for thegit stashthe command is as follows:

git stash list [<opciones>]git stash show [<stash>]git stash drop [-q|--quiet] [<stash>]git stash ( pop | apply ) [--index] [-q|-- quiet] [<stash>]git stash branch <branchname> [<stash>]git stash [save [-p|--patch] [-k|--[no-]keep-index] [-q|-- quiet][-u|--include-untracked] [-a|--all] [<mensaje>]]git stash cleargit stash create [<mensaje>]git stash store [-m|--message <mensaje>] [-q|--quiet] <compromiso>
ALSO READ: Git Cherry Pick Commit Examples Explained [RIGHT]

When to use the git stash command

Working with different functions in parallel doesn't make a developer happy, but sometimes it happens. So at some point we need to stop working on one branch and switch to another. However, sometimes we have some changes that are not ready to be committed because they are partial, inconsistent or even uncompilable.

So you can use the git stash command if:

  • You don't want to make experimental changes
  • You don't want to lose your local changes with a hard reset

How the git stash works

The standard syntax for creating a stash in Git isgit stash <options>

The images in this section provide a visual representation of how to create a standard stash (with no options). In this case, the asterisk (*) denotes a change made to the working directory and staged to the staging area since you last committed.

git stash explained in detail with examples | GoLinuxCloud (1)

Now run yoursgit stashDomain:

$ git stash

The image below shows what happens conceptually. Git creates a stash of the staging area and working directory with the uncommitted change. It also resets the locale to the last commit (HEAD).

You have now stashed your running changes and your local environment is clean (in sync with the last commit). This is the basic operation.

Notice

git stash explained in detail with examples | GoLinuxCloud (2)

Git-Archiv-Workflow

Here is an example git stash workflow to understand the different stages:

# Your changes before savingadd git# Save the changes (stash)git stash save "Save editing changes to this file"# List of hidden changesGit hide list# At this point, your local repository is cleanGit-Status# To undo the stash by popping the stashgit escondite pop# Check if the stash has been openedGit hide list# Check for pending changes before savingGit-Status
ALSO READ: git renames branch CORRECTLY [3 examples]

Save uncommitted changes

How to hide all changes

I have this depotgit_examplesunder which I createdgit_stashDirectory. I will perform various operations on this directory throughout this article.

Here I made some changes to one of the scriptsgit_stashDirectory:

deepak@ubuntu:~/git_examples$ git statusOn branch my-feature-branchChanges not being staged for commit: (use "git add <file>..." to update what is being committed) (use " git restore <file>.. ." to discard changes to the working directory)changed: git_stash/create_users.shno changes added to commit (use "git add" and/or "git commit -a")

But suddenly it occurred to me that I also have to work on another project that has priority. Now I can't commit these changes because they are incomplete, so let me stash these changes while I work on another project:

deepak@ubuntu:~/git_examples$ git is hereWorking directory and index status WIP saved in my-feature-branch: 1b6369c Added create_users.sh script

so now minegit_examplesrepo is clean as new:

deepak@ubuntu:~/git_examples$ Git-StatusAuf dem Zweig my-feature-branchnothing to commit, clean working tree

The following changes are currently hidden:

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}: WIP de my-feature-branch: 1b6369c Look at the create_users.sh script

In the next few sections, you'll learn how to load changes from the stash. But before that, let's learn more about tracked and untracked files before moving on to the next section.

ALSO READ: Git Command Cheat Sheet [One STOP Solution]

Save only selected files (git stash --patch)

By default, git stash hides all uncommitted changes, but if you just want to hide some of the uncommitted changes, you can use-p|--parksDispute. This will prompt you to save each of the files.

Notice

For example, here are some changes I made to my branch:

git stash explained in detail with examples | GoLinuxCloud (3)

Let's run Stash with- Patch:

deepak@ubuntu:~/git_examples/git_stash$ git stash -pdiff --git a/git_stash/create_users.sh b/git_stash/create_users.shindex 01dd0d8..28c2576 100644--- a/git_stash/create_users.sh+++ b/git_stash/ create_users.sh@@ -1 +1,3 @@ ## Este script crea usuarios+## Created on 07/19/2021+## Modified on 07/20/2021(1/1) Save this block [y,n,q,a,d,e,?]? YSaved working directory and index status WIP on main: 1b6369c Added create_users.sh script

you can hit?for a complete list of stub commands. The generally useful ones are:

  • /: Search for a chunk using regular expressions
  • ?: Help
  • Norte: do not hide this piece
  • q: exit (all already selected chunks will be saved)
  • s: Splits this chunk into smaller chunks
  • j: Save this part

So this is where we saved our work for this particular file.crear_usuarios.shwhile the other is still in our local repository andhas not yet been hidden(as expected):

deepak@ubuntu:~/git_examples/git_stash$ git statusOn branch mainYour branch will be updated with 'origin/main' Changes to be made: (use "git restore --staged <file>..." to remove the stage)new file: create_groups.shChanges not ready to commit: (use git add <file>... to update what is about to be committed) (use git restore <file>... to update working directory changes to discard)changed: create_groups.sh

List hidden changes:

deepak@ubuntu:~/git_examples/git_stash$ Git list hiddenstash@{0}:WIP in main: 1b6369c Added create_users.sh script
ALSO READ: How to Disorganize Files in Git Without Losing Changes

What are tracked and untracked files in Git?

Before proceeding, you should be familiar with crawled and non-crawled files.

Notice

This designation refers to whether or not Git knows about the file; H. has anyone added this file to git before? If that file has at least been added (rather than removed) to the staging area at some point, then Git knows about it and maintains a version of it, so so be ittrackedby git. Otherwise the fileno pursuitand Git doesn't know about it and doesn't maintain any version of it.

An example of an untracked file would be a new file that has not been added to Git. files in the.ignore.gitFile doesn't count as untracked because Git ignores it.

untracked files from Git Stash

By default, untracked files are ignored when hiding content with Git. In order for Git to store files without tracking, it is necessary to have the-tu(--Include without tracking) Possibility. This option includes untracked files from the working directory in the stash.

Let's create a new file ingit_stashBinder:

deepak@ubuntu:~/git_examples$ toque git_stash/create_groups.sh

This file is marked as untracked because it has not yet been added to the repository:

deepak@ubuntu:~/git_examples$ git statusOn branch my-feature-branch Untracked files: (use "git add <file>..." to include in what is being committed)git_stash/create_groups.shnothing added to commit but untracked files are present (use "git add" to track)

Let's try to hide the changes without additional arguments:

deepak@ubuntu:~/git_examples$ git is hereNo local changes to save

Unsurprisingly, the cloak didn't recognize the untracked files.

ALSO READ: git Undo Commit RIGHT [5 Different Ways]

So we have to use explicitly-tuargument withgit stashCommand to hide untracked changes as well:

deepak@ubuntu:~/git_examples$ git alijo -uWorking directory and index status WIP saved in my-feature-branch: 1b6369c Added create_users.sh script

List available stock:

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}:WIP in my-feature-branch: 1b6369c Added create_users.sh scriptstash@{1}:WIP in my-feature-branch: 1b6369c Added create_users.sh script

Provide a description for stash commits (git stash save)

Usually when Git hides something, it has a generated comment associated with the element, like this:

Notice

stash@{#}: WIP bei <branch>: <SHA1 of last commit> <last commit message>

WIP stands for work in progress.

Let's make a few more changes to my existing script:

deepak@ubuntu:~/git_examples$ echo "## Description: This is a test script for creating users" >> git_stash/create_users.sh

This time we save our changes with a custom message:

deepak@ubuntu:~/git_examples$ git stash save "Working on issue #7211 to create users with create_users.sh"Saved working directory and index status In my-feature-branch: working on issue #7211 about creating users with create_users.sh

As you can see, we now have a more meaningful form of hidden changes:

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}:In my-feature-branch: working on issue #7211 on creating users with create_users.shstash@{1}:WIP in my-feature-branch: 1b6369c Added create_users.sh scriptstash@{2}:WIP in my-feature-branch: 1b6369c Added create_users.sh script
ALSO READ: Git Fetch Workflow Explained [With Simple Examples]

Check what's in stock

Once you've saved your changes, you'll be able to see what you have in the queue. To do this, use the list option of the stash command, which we've used a few times above:

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}:In my-feature-branch: working on issue #7211 on creating users with create_users.shstash@{1}:WIP in my-feature-branch: 1b6369c Added create_users.sh scriptstash@{2}:WIP in my-feature-branch: 1b6369c Added create_users.sh script

In the standard output I have the name of the hidden item in the list(Reservations@{#}), followed by information about the branch that was current when the stash was created, and then the latest commit that the stash was based on.

This information is useful up to a point, but what if you want to see more details about an item in your stash? It turns out that Stash supports options like the ones you use with the git log command. Knowing this gives you several options for obtaining additional information. For example, you can start using--onlineOption as used below that shows you the abbreviated SHA1 values ​​for each storage element:

deepak@ubuntu:~/git_examples$ git stash list --oneline775caa9(refs/stash) refs/stash@{0}:In my feature branch: Working on issue #7211 on creating users with create_users.shd73cda6References/stash@{1}:WIP in my-feature-branch: 1b6369c Added create_users.sh script57f436e References/stash@{2}:WIP in my-feature-branch: 1b6369c Added create_users.sh script

Now you can use themGit-Stash-ShowSubcommand and pass it the SHA1 value to see a brief summary of the changes that just happened:

deepak@ubuntu:~/git_examples$ git stash show 775caa9git_stash/create_users.sh | 1 + 1 file modified, 1 insert (+)

You can add the for even more information-Page(Patch) to view the patch style differences included in the change:
git stash explained in detail with examples | GoLinuxCloud (4)

ALSO READ: git remote add explained [simple examples]

Restore hidden changes (unstash)

When retrieving saved changes from the stash, Git attempts to reapply the saved staging changes to your local environment's staging area and your working directory's saved changes to your local environment's working directory. There are two ways to do this:inquiryjPop.

Notice

These options can be used on any branch, not just the branch where the original backup was made.

git stash apply command

The apply option tries to commit the changes back.while a copy of the items as an item still remains in the queue. Note that you can apply from any item to any position in the queue by referencing the name in the stash(Reservations@{#}). Unlike a more formal queue, you don't just have to drag items from the first or last position in the queue.

An application example would be:

deepak@ubuntu:~/git_examples$ git stash apply stash@{1}

Example output from my terminal:
git stash explained in detail with examples | GoLinuxCloud (5)

If the command is successful, your staging area and working directory are updated with the contents of the stash item and Git runs a git status command to show you the updated status.

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}: in my function branch:Working on issue #7211 on creating users with create_users.shstash@{1}: WIP in my-feature-branch: 1b6369c Added create_users.sh scriptstash@{2}: WIP in my-feature-branch: 1b6369c Added create_users.sh script

Let me save this change again:

deepak@ubuntu:~/git_examples$ git alijo -uWorking directory and index status WIP saved in my-feature-branch: 1b6369c Added create_users.sh script

So now we have a total of 4 hidden changes:

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}:WIP in my-feature-branch: 1b6369c Added create_users.sh scriptstash@{1}:In my-feature-branch: working on issue #7211 on creating users with create_users.shstash@{2}:WIP in my-feature-branch: 1b6369c Added create_users.sh scriptstash@{3}:WIP in my-feature-branch: 1b6369c Added create_users.sh script

USE:

There is also a git apply command that is used to apply patches, so be careful not to confuse these two commands.

ALSO READ: Setting Up GitHub Using Visual Studio Code [Step-By-Step]

git stash pop command

The popup option works like the app option, butRemove item from queueafter updating your environment. As with the Apply option, you can place an item from any position in the queue.

An example would be:

deepak@ubuntu:~/git_examples$ git stash pop stash@{2}

Example output from my terminal:
git stash explained in detail with examples | GoLinuxCloud (6)

Notice that in the queue because you made the pop-inElement 2, you now have three items:

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}:WIP in my-feature-branch: 1b6369c Added create_users.sh scriptstash@{1}:In my-feature-branch: working on issue #7211 on creating users with create_users.shstash@{2}:WIP in my-feature-branch: 1b6369c Added create_users.sh script

Merge conflicts when restoring hidden changes

When you're ready to move the contents of the queue back to your local environment, you probably have other updates in your local environment that weren't there when you originally saved them. If there are potential merge conflicts between what you're trying to push or pull and what's currently in your local environment, how Git handles it depends on the circumstances.

Notice

For example, you saved the same change twice above. So let me make one of the hidden changes:

deepak@ubuntu:~/git_examples$ git stash pop stash@{2}deepak@ubuntu:~/git_examples$ git add git_stash/create_groups.shdeepak@ubuntu:~/git_examples$ git commit -m "Creado nuevo script para agregar grupos" git_stash/create_groups.sh

Now let me try to open another stash for the same change:

deepak@ubuntu:~/git_examples$ git stash pop stash@{0}git_stash/create_groups.sh already exists, no validation error: Untracked files could not be restored from stash. The stash entry is retained in case you need it again.

Unsurprisingly, Git doesn't allow this since there are locally unmerged files. The solution isFix merge issues firstand then organize the fixed files.

ALSO READ: Changing git commit CORRECT [Simple Examples]

Delete hidden changes

You can usegit stash drop <stash_id>to remove saved changes. For example, since I already created minecrear_grupos.shScript so I delete the duplicate stash change:

deepak@ubuntu:~/git_examples$ git stash drop stash@{0}Verlorenes Stash@{0} (4e1aaa8397d07440029407e0817a4a99abed177e)

SPUR:

If you don't specify the stash id, the last stash is deleted first. for example offstash@{0}jstash@{1},stash@{0}is removed first.

List available stock:

deepak@ubuntu:~/git_examples$ Git-Stash-Listestash@{0}:In my-feature-branch: working on issue #7211 on creating users with create_users.shstash@{1}:WIP in my-feature-branch: 1b6369c Added create_users.sh script

Let me go ahead and clear the entire stash.

deepak@ubuntu:~/git_examples$ Git-Stash-DropDeleted References/Storage@{0} (fd1f432e03ccd9f1011341ef9281a8b1e55e48a4)deepak@ubuntu:~/git_examples$ Git-Stash-DropRefs descartados/almacenamiento@{0} (775caa9105d9d20b57e1101a29353a31900f5c41)

Create a branch from a given stash

You can also create a new branch from one of your hidden changes using the following syntax:

Git-Stash-Zweig "BRANCH_NAME" stash@{#}

For example I have the following hidden changes:

deepak@ubuntu:~/git_examples/git_stash$ Git list hiddenstash@{0}:Main: Added creation date in create_users.sh

I will create a new branchfix-7211-problemafrom this stock:

git stash explained in detail with examples | GoLinuxCloud (7)

If we create a branch from any stash, this action will pull a new branch based on the commit you created your stash from and then display the changes saved in it.

deepak@ubuntu:~/git_examples/git_stash$ Git list hidden

A new branch has been created and our fallback list is now empty:

deepak@ubuntu:~/git_examples/git_stash$ rama git* Fix-7211-Problemmain branch of my function
ALSO READ: git HEAD~ vs HEAD^ vs HEAD@{} Explained with examples

Continue

In this Git tutorial, we cover the git stash command, which allows you to freeze your current work without having to commit an unfinished change. This will help you develop good programming habits, like the one that tells you not to make unfinished changes.

We cover the following topics in detail with several examples:

  • What is Git Stashing and how does it work?
  • When should you use the git stash command?
  • Different ways to save your changes with cloaking
  • Different ways to restore your uncloaking changes
  • Delete hidden changes
  • Create a branch from specific hidden changes

Continue reading

What is the intended use case for Git Stash?

Top Articles
Latest Posts
Article information

Author: Otha Schamberger

Last Updated: 03/24/2023

Views: 6709

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.