Saving Your Work in Git: A Guide to the Stash Operation

Learn how to temporarily save your uncommitted changes in Git using the stash operation. This feature allows you to switch to other tasks without losing your progress, making it a valuable tool for managing your workflow.



Git - Stash Operation

Imagine you are implementing a new feature for your product. Your code is still in progress when suddenly a customer escalation arises. You need to set aside your new feature work for a few hours, but you cannot commit your partial code or discard your changes. What you need is temporary space to store your in-progress work, which you can later commit.

In Git, the stash operation allows you to take your modified tracked files, stage those changes, and save them on a stack of unfinished changes that you can reapply at any time.

Syntax

[jerry@CentOS project]$ git status -s
M string.c
?? string
        

Now, you want to switch branches for the customer escalation but don’t want to commit what you’ve been working on yet. So, you’ll stash your changes using the following command:

Stashing Changes

[jerry@CentOS project]$ git stash
Saved working directory and index state WIP on master: e86f062 Added my_strcpy function
HEAD is now at e86f062 Added my_strcpy function
        

Your working directory is now clean, and all your changes are saved on a stack. You can verify this with the git status command:

Check Status After Stashing

[jerry@CentOS project]$ git status -s
?? string
        

Now you can safely switch branches and work on the customer escalation. To view a list of your stashed changes, use the following command:

List Stashed Changes

[jerry@CentOS project]$ git stash list
stash@{0}: WIP on master: e86f062 Added my_strcpy function
        

After resolving the customer escalation, you can return to your new feature and retrieve your half-done code by executing the git stash pop command. This command removes the changes from the stack and applies them to your current working directory:

Pop Stashed Changes

[jerry@CentOS project]$ git stash pop
        

The above command will produce the following result:

Output

# On branch master
# Changed but not updated:
# (use "git add ..." to update what will be committed)
# (use "git checkout -- ..." to discard changes in working directory)
#
#
modified: string.c
#
# Untracked files:
# (use "git add ..." to include in what will be committed)
#
#
string
no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (36f79dfedae4ac20e2e8558830154bd6315e72d4)
        

Finally, you can check the status once more to see that your changes have been reapplied:

Final Status Check

[jerry@CentOS project]$ git status -s
M string.c
?? string