The git revert
command is also used to undo changes made to a repository. However, it does not remove these changes from Git history. It inverts the changes made after the specified commit. Then, it creates a new commit with the resulting changes.
Key takeaways:
We sometimes need to undo
git add
when files are staged by mistake (e.g.,.env
,node_modules
, or unfinished edits).Use
git reset <filename>
orgit reset
to unstage one or all files.Use
git restore --staged <filename>
orgit restore --staged .
as a newer, safer alternative.Both commands remove files from the staging area but keep your changes in the working directory.
After unstaging, you can edit files further and re-stage them when ready.
When we're working with Git and accidentally use git add
to stage files that aren't ready to be committed, we need to know how to undo it. This Answer explains the commands to unstage files, so we can fix our mistake without losing any of our work. We'll cover both the classic git reset
command and the newer, safer git restore --staged
command.
Before diving into how to undo git add
, it’s essential to understand the staging area (also known as the index) in Git:
Working directory: This is where we’ll make changes to files.
Staging area: This is where we prepare changes to be committed. When we run git add
, we move changes from the working directory to the staging area.
// to stage a filegit add filename// to stage all changed filesgit add .
Repository: This is where your committed changes are stored. After you run git commit
, the changes in the staging area are saved to the repository.
git add
Sometimes, we may move changes to the staging area unintentionally and will need to undo this operation. For this, we can use the following two methods:
Both of these methods unstage the files from the staging area.
git reset
commandgit reset filename
git reset
After running git reset
, the changes remain in our working directory, but they are no longer in the staging area.
git restore --staged
commandgit restore --staged filename
git restore --staged .
Hands-on practice is essential for truly understanding and mastering new concepts. Just as Donald Knuth suggested:
“The only way to learn about new things is to do them; the way to learn usability is to make something usable.”
Let’s run the following commands in the terminal given below to first add files to the git
local repository and then reset them from the staging area:
We will first create three files with some text, such as README.md
, first.html
, and last.html
.
To add files for Git to track, use the git add filename
command.
Next, run the git reset
command to remove a file from git add
.
cd gitgit initecho "# My README.md file" > README.mdecho "# My second file" > first.htmlecho "# My third file" > last.htmlgit add .git ls-filesgit reset filenamegit ls-files
Let’s execute the above commands one by one and see how to undo git add
:
Haven’t found what you were looking for? Contact Us
Free Resources