Git Reset
The git reset command moves the current branch to another commit. It is mostly used to undo the last commits. It has three modes: --soft, --mixed (default) and --hard. They are the same in moving the branch, but different in what they do with your files.
The three modes
| Mode | Branch moves back | Staging area | Working directory |
|---|---|---|---|
--soft | Yes | Keeps the changes staged | Not changed |
--mixed (default) | Yes | Cleared (changes unstaged) | Not changed |
--hard | Yes | Cleared | Changes are deleted |
Prepare an example
$ git log –oneline
a7d3451 (HEAD -> main) Add multiplication
48e6c2d Add subtraction
674223b Add addition
git reset –soft
It undoes the commit, but keeps the changes in the staging area. Good when you want to redo the commit, or join some commits into one.
$ git reset –soft HEAD~1
$ git log –oneline
48e6c2d (HEAD -> main) Add subtraction
674223b Add addition
$ git status -s
M ops.txt
$ cat ops.txt
add
subtract
multiply
The last commit is gone, but the line “multiply” is still in the file and is staged. We can commit it again with the same message:
$ git commit -q -C ORIG_HEAD
$ git log –oneline
8855dfd (HEAD -> main) Add multiplication
48e6c2d Add subtraction
674223b Add addition
git reset –mixed (default)
It undoes the commit and also unstages the changes, but the file is not changed.
$ git reset HEAD~1
Unstaged changes after reset:
M ops.txt
$ git log –oneline
48e6c2d (HEAD -> main) Add subtraction
674223b Add addition
$ git status -s
M ops.txt
$ cat ops.txt
add
subtract
multiply
$ git commit -q -a -C ORIG_HEAD
$ git log –oneline
4952dc3 (HEAD -> main) Add multiplication
48e6c2d Add subtraction
674223b Add addition
git reset –hard
This undoes the commit and also deletes the changes from the files. Use it very carefully.
$ git reset –hard HEAD~1
HEAD is now at 48e6c2d Add subtraction
$ git log –oneline
48e6c2d (HEAD -> main) Add subtraction
674223b Add addition
$ git status -s
$ cat ops.txt
add
subtract
The line “multiply” is gone from the file, too. The commit can still be found with git reflog for some time, see Git Reflog.
Reset one file (unstage)
git reset HEAD file.txt
It does the same as git restore --staged file.txt.
Reset to a specific commit
git reset --hard a3f9c1e
git reset --hard origin/main
The second line makes your local branch the same as the remote one, and throws away your local commits and changes.
Reset or revert?
Reset changes the history. So do not use it on commits which are already pushed and shared. For those, use git revert, which makes a new commit that undoes the old one.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |