One of the key features of git is that you can revert any changes you make with just one command. This is virtually impossible to do without the use of a version control system. Unless you remember all the changes by heart. In this tutorial, we'll talk about rolling back changes that have been made in the working directory but haven't yet been committed.
Important! Rolling back uncommitted changes is irreversible. There is no way to get these changes back, so be extremely careful.
Untraceable files
The simplest situation. You added new files to the repository (or generated them somehow) and realized you didn't need them. In this case, you can perform a cleanup:
mkdir one
touch two
git status
On branch main
Your branch is up to date with 'origin/main'.
# In principle, empty directories are not added to git
# Physically the directory "one" is in the working directory,
# but it's not in git and it ignores it
Untracked files:
(use "git add <file>..." to include in what will be committed)
two
# Performing the cleanup
# -f – force, -d – directory
git clean -fd
Removing one/
Removing two
Fun fact: not many programmers know about this command. You can even surprise experienced people.
Changed files in the working directory
The git restore
command is used to undo changes to such files. And git itself reminds you of this when checking the status:
echo 'new text' > INFO.md
git status
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)
# Below it says how to undo the change
(use "git restore <file>..." to discard changes in working directory)
modified: INFO.md
# Cancel
git restore INFO.md
Changes staged for commit
Files staged for a commit can be handled in different ways. The first option is to undo changes completely, the second option is to undo indexing only, without changing the files in the working directory. The second is useful if we need the changes but don't want to commit them now.
echo 'new text' > INFO.md
git add INFO.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)
modified: INFO.md
This is where git helps again. When the status is displayed, it shows us the command we need to return the changes to the working directory:
git restore --staged INFO.md
git status
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: INFO.md
Now, if necessary, you can run git restore
and permanently undo the changes to selected files.
Do it yourself
Follow all of the steps in the lesson