Hard and Soft Reset in git

There are two types of git reset – hard and soft. Let us look into them hands-on.

Consider this initial arrangement of a repository with the name repoone. It has four commits, as shown. There are a total of six files and one directory, as shown.

Use “git show” on the latest commit. You would see that it has added two files filefive and filesix.

~/repoone$ git log --oneline
908d6ac (HEAD -> main, origin/main, origin/HEAD) Third commit in main
42296d0 Second commit in main
453424e This is first commit
2673111 Initial commit

~/repoone$ ls
dirone  filefive  filefour  filesix  filethree  filetwo  README.md

~/repoone$ git show 908d6ac
commit 908d6ac779f38123751ddd70d6107bb43cc832a1 (HEAD -> main, origin/main, origin/HEAD)
Author: paperspace <Code Version Master>
Date:   Sat Sep 10 05:15:28 2022 +0000

    Third commit in main

diff --git a/filefive b/filefive
new file mode 100644
index 0000000..e69de29
diff --git a/filesix b/filesix
new file mode 100644
index 0000000..e69de29

Use git reset –soft <commit>. “git log” shows that the commit reverses, meaning that the code changes have reversed. But the files are still preserved. If you want to add them back or use them in any manner, you can do so.

~/repoone$ git reset --soft 42296d0

~/repoone$ git log --oneline
42296d0 (HEAD -> main) Second commit in main
453424e This is first commit
2673111 Initial commit

~/repoone$ ls
dirone  filefive  filefour  filesix  filethree  filetwo  README.md

~/repoone$ git status
On branch main
Your branch is behind 'origin/main' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   filefive
        new file:   filesix

Instead, use git reset –hard <commit>. “git log” shows that the commit reverses, meaning that the code changes have reversed. You can also see that all the respective files and related code is completely removed and reset.

~/repoone$ git reset --hard 42296d0
HEAD is now at 42296d0 Second commit in main

~/repoone$ git log --oneline
42296d0 (HEAD -> main) Second commit in main
453424e This is first commit
2673111 Initial commit

~/repoone$ ls
dirone  filefour  filethree  filetwo  README.md