Imagine this: you're working on an important task and have changed quite a few files. At this point, an urgent task arises to make a change in the source code that's unrelated to what you're currently working on. Your changes are not ready yet and should not go into the repository. What to do?
In the simplest case, if your changes don't overlap with the changes you made during the urgent task, you can make the necessary corrections, add them to the index, commit them, and run them. But this is usually inconvenient and not always possible. What if you need to make changes in the files you're working with right now?
This situation occurs regularly with experienced developers and, fortunately, it is easily resolved. Git has a set of commands that allow you to "hide" changes in the working directory and restore them when needed. Let's give it a try:
touch FILE.md
git add FILE.md
git status
On branch main
Your branch is up to date with 'origin/main'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: FILE.md
# Hide the files. After this command, all the changed files will disappear
# whether they are added to the index or not
git stash
Saved working directory and index state WIP on main: e7bb5e5 update README.md
git status
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
git stash
does not delete files, they go to a special place inside the .git directory to «be saved». This command does not touch the new files as they are not yet part of the repository.
After you have made all the necessary changes on a clean working directory, you can revert the hidden changes with the git stash pop
command:
# Restoring
git stash pop
On branch main
Your branch is up to date with 'origin/main'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: FILE.md
Dropped refs/stash@{0} (b896d4a0126ef4409ede63857e5d996953fe75c5)
# Checking
git status
On branch main
Your branch is up to date with 'origin/main'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: FILE.md
The files came back since they were in the stash.
Stash in git works like a stack. It allows you to save any number of changes inside and restore them in reverse order:
git stash
# Modifying the files
git stash
# The latest changes will be returned
git stash pop
# The penultimate changes will be returned
git stash pop