The git reset command is used to revert versions and can specify which commit version to revert to.
The syntax for the git reset command is as follows:
git reset [--soft | --mixed | --hard]
--mixed is the default and can be omitted. It is used to reset the staged files to match the last commit, while the working directory files remain unchanged.
git reset
Example:
$ git reset HEAD^ # Revert all content to the previous version
$ git reset HEAD^ hello.php # Revert the version of hello.php to the previous version
$ git reset 052e # Revert to a specific version
The --soft parameter is used to revert to a specific version:
git reset --soft HEAD
Example:
$ git reset --soft HEAD~3 # Revert to three versions ago
The --hard parameter cancels all uncommitted changes in the working directory, resets both the staging area and working directory to the previous version, and deletes all previous commit information:
git reset --hard HEAD
Example:
$ git reset --hard HEAD~3 # Revert to three versions ago
$ git reset βhard bae128 # Revert to a specific version, deleting all information before that revert point.
$ git reset --hard origin/master # Reset the local state to match the remote
Note: Use the --hard parameter with caution, as it will delete all information before the revert point.
HEAD Explanation:
- HEAD represents the current version
- HEAD^ represents the previous version
- HEAD^^ represents two versions ago
- HEAD^^^ represents three versions ago
- And so on...
You can also use the tilde (~) followed by a number:
- HEAD~0 represents the current version
- HEAD~1 represents the previous version
- HEAD~2 represents two versions ago
- HEAD~3 represents three versions ago
- And so on...
git reset HEAD
The git reset HEAD command is used to unstage content.
First, let's modify the README file with the following content:
# Git Test
#
Modify the hello.php file to:
<?php
echo ': www.';
echo ': www.';
echo ': www.';
?>
Now, after modifying both files, they are both staged. We want to unstage one of them. The operation is as follows:
$ git status -s
M README
M hello.php
$ git add .
$ git status -s
M README
M hello.php
$ git reset HEAD hello.php
Unstaged changes after reset:
M hello.php
$ git status -s
M README
M hello.php
Now, if you execute git commit, only the changes to the README file will be committed, while hello.php will not be.
$ git commit -m 'Modify'
Modify
1 file changed, 1 insertion(+)
$ git status -s
M hello.php
You can see that the changes to hello.php were not committed.
At this point, we can use the following command to commit the changes to hello.php:
$ git commit -am 'Modify hello.php file'
Modify hello.php file
1 file changed, 1 insertion(+)
$ git status
On branch master
nothing to commit, working directory clean
In short, execute git reset HEAD to unstage content that was previously added with git add but you do not want to include in the next commit snapshot.
YouTip