How to Remove Files from Git Commit
Sometimes you stage your files for commit and want to remove files from your commit to make more modifications. In this tutorial, we will show how you can effectively remove files from your Git commits discussing some scenarios.
Removing file from previous commit
Let’s discuss our first scenario. Here is what you need to do:
Removing file and keeping on desk
If you only want to remove a file from the previous commit and keep it on disk the git reset command can help:
git reset --soft HEAD^
git reset --soft HEAD~1
Then, you can reset the files you no longer need to remove them from the commit:
git reset HEAD path/to/unwanted_file
You can git commit again and even use the same commit message:
git commit -c ORIG_HEAD
Deleting file from last commit
The second scenario discusses the situation when it is your last commit, and you want to delete the file.
Deleting file from index
You can use the git rm command in order to delete the file from the staging area. The --cached option indicates the file to be removed from the cached area:
git rm --cached <file>
When you finish the modifications, you can commit your changes again with the --amend option:
git commit --amend
If done with the work, you can check whether the files are removed from the repository and the does not appear in the new file:
git ls-files <file1> <file2>
The git reset Command
The git reset command is used to undo changes. It passes the HEAD reference pointer and the current branch reference pointer.
The --soft argument updates reference pointers and stops the reset. However, it doesn’t affect the staging index and the working directory. A soft reset resets only the commit history. By default, it is invoked with HEAD as the target commit.
The git rm Command
The git rm command removes specific files or a collection of files from a git repository. The primary function of git rm is removing tracked files from the staging area (also called index). The git rm is also used for deleting files from both the staging index and the working directory. But a file can not be removed only from the working directory. However, git rm does not remove branches.
The git commit Command
The git commit command keeps all the currently staged changes. Commits are for capturing the current state of the project. Committed snapshots are regarded as secure versions of a project because Git asks before changing them. The git add command promotes changes to the project that will be then stored in a commit before executing the git commit command. The--amend option changes the last commit. Staged modifications are added to the previous commit. This argument opens the system's configured text editor and changes the previously specified commit message.