Sometimes you may have mistakenly added one or more files to your git repository and want to undo those changes before committing the changes. You may need to revert recently added files in git before commit. In this article, we will look at how to undo git add before commit. It will help you untrack any files that you may have inadvertently added. You can also use it to remove one or more directories from the index.
How To Undo Git Add Before Commit
It is very easy to undo git add before commit using git reset command.
Let us say you have mistakenly added file test.txt using the following command.
$ sudo git add test.txt
Here is the command to undo git add for this specific file. You can also use the following commands with directories.
$ sudo git reset filename
that is
$ sudo git reset test.txt
This command is useful if you want to undo only 1 addition.
If you want to remove a directory /product from the index then use the path to directory instead of a file name.
$ sudo git reset /product
Also read : How to Upgrade PHP version in Ubuntu
If you want to undo all files added after last commit just enter
$ sudo git reset
When you omit the filename from git reset command it reverts all files that have been added after last commit. This is useful if there are many files that you want to remove from the add.
Also read : How to list all services using systemctl
You can also achieve the same result using git rm command as shown below.
$ sudo git rm filename
that is
$ sudo git rm --cached test.txt
Also read : How to Install AWS CLI in Ubuntu
For git <1.8.2
The above commands work for all git versions after 1.8.2. However, if you still use one of the older git versions, then you need to use the following command to remove a single file from the index
$ sudo git reset HEAD filename
that is
$ sudo git reset HEAD test.txt
Also read : How to Tar a file in Linux
Similarly, if you want to remove multiple files from index run the above command without specifying the filename.
$ sudo git reset HEAD
However, please note, the above commands will give an error if HEAD is not defined. This happens if you have not made any commits to your repository so far, if you have created a branch named HEAD, which is not advisable.