What is the purpose of Git Stash command ?
In this sneppet you will learn what is Git Stash command and the when to use git stash command.
Git Stash Command
Use git stash command when you wanted to save the current state of your working directory and the index but wanted to go back to a clean working directory.
This command saves your local repository changes away and reverts the working directory to match the HEAD commit.
Git Stash Use Case
Let’s say your current working directory is messed up with the changes you made in your branch. But still you wanted to record the current state of your working directory before you pull changes using “git pull” command from the Git remote repository.
$ git stash Saved working directory and index state WIP on main: ef8115c Merge branch 'main' of https://github.com/sneppets/gitdemo
The local changes that are stashed away by this command can be listed with “git stash list” command, inspected with “git stash show” command.
$ git stash list stash@{0}: WIP on main: ef8115c Merge branch 'main' of https://github.com/sneppets/gitdemo
$ git stash show file1.txt | 1 + 1 file changed, 1 insertion(+) If you want to pull latest changes from git run git pull
Now, run “git pull” command. Since you had stashed your local changes you should not see any conflict and could see your local branch is already up to date.
$ git pull Already up to date and restored (potentially on top of a different commit) with git stash apply.
Please note, you also see a message output saying “restored with git stash apply”. Now you can restore stashed changes to your local branch.
$ git stash apply On branch main Your branch is up to date with 'origin/main'. Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: file1.txt no changes added to commit (use "git add" and/or "git commit -a")
Once you restore the changes, you can add the modifications using “git add” command and commit the changes using “git commit” command.
$ git add .
$ git commit -m "new changes in local" [main 5204209] new changes in local
Finally, run “git push” command to push the changes to remote repository.
You can also check another use case which I explained in previous tutorial “Usage of git stash command while creating new branch from a tag in Git“.
Hope you find this sneppet useful 🙂
You’ll Also Like
- Throw away the local commits from your branch in Git ?
- Your branch and ‘origin/main’ have diverged, how to fix this ?
- How to connect to Github using SSH ?
- How do you do undo git reset –hard HEAD^ and revert to previous commit ?
- Git – How to compare files in two different branches
- Git not working with a proxy server – gnutls_handshake() failed
- npm ERR! enoent spawn git ENOENT
- GitHub unable to access HTTPS and SSL routines error
- Remove http and https proxy settings of npm and git ?
- Fix Nodejs Error: ENOENT: no such file or directory