Git Reset -- Hard: Test Documentation

1. Initial Setup
Cloning the Repository
git clone https://github.com/RScrafted/test.git --progress
cd test
2. First Commit: Addition
Editing the Script
vi calculator.sh
a=5
b=5
echo "ADDITION: $((a + b))"
:wq
Staging and Committing
git add calculator.sh
git commit -m "Addition"
Checking Status and Log
git status
git log
3. Second Commit: Hello World
Editing the Script Again
vi calculator.sh
a=5
b=5
echo "ADDITION: $((a + b))"
echo "Hello World"
:wq
Staging and Reviewing Changes
git add calculator.sh
git diff
Committing the Second Version
git commit -m "Second Version"
git push origin main
Checking Status and Log
git status
git log
4. Resetting --hard to Previous Commit (locally)
Performing the Reset
git reset --hard ab4408dce770c028f96c1dfaf83f2f17e3731475
Output:
HEAD is now at ab4408d Addition
Verifying the Reset
git log
Result: Only the "Addition" commit is visible.
5. Pushing to GitHub After Reset
Attempting to Push
git push -u origin main
Error Message:
To https://github.com/RScrafted/test.git
! [rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'https://github.com/RScrafted/test.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. If you want to integrate the remote changes,
hint: use 'git pull' before pushing again.
Explanation
The error occurs because the local branch was reset to an earlier commit (ab4408d
), causing it to diverge from origin/main
. Git rejects the push to prevent overwriting remote history.
6. Resolving the Push Conflict
Option 1: Pull First (Not Recommended for Hard Reset)
git pull --rebase
git push -u origin main
Note: This undoes the effect of git reset --hard
, as it reintroduces remote commits.
Option 2: Force Push (Recommended for Hard Reset)
git push origin main --force
Warnings:
This action overwrites the remote branch to match your local history.
It may affect collaborators who have pulled the discarded commits.
Safe for solo projects or coordinated resets.
Summary: This tells GitHub to replace the remote main
branch with the local version.
7. Additional Testing: Branch Versions
Scenario
Created three commits: "First", "Second", and "Third".
Reset to Second Version
After resetting the third version to the second:
git reset --hard <second-commit-id>
git log
Result: Only "First" and "Second" commits are visible.
Reset to First Version
After resetting to the first commit:
git reset --hard <first-commit-id>
git log
Result: Changes from "Second" and "Third" are removed.
Subscribe to my newsletter
Read articles from Rachit Sheth directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Rachit Sheth
Rachit Sheth
A cloud enthusiast ๐ฉ๏ธ and IT whiz ๐งโโ๏ธ. Passionate about Photography!