You can undo or revert an unintended merge in your local git repository before it’s pushed to remote repository using git reset –hard command.
Example:
Create a new local git repository:
1 2 |
## Create a new local git repository git init myrepo && cd myrepo |
Create your first git commit on the default branch:
1 2 3 4 |
## add a new file and commit echo "hello world" > file1 git add file1 git commit -m "commit1" |
Create a new branch:
1 2 |
## Create a new branch named feature git checkout -b feature |
Create your second commit on the feature branch:
1 2 3 |
echo "welcome to cloudaffaire" > file2 git add file2 git commit -m "commit2" |
Merge and delete the feature branch:
1 2 3 4 |
## Merge and delete the feature branch git checkout master git merge -m "commit3" feature git branch -d feature |
Check files in the master branch:
1 2 |
## Check file in master branch ls ## returns file1 and file2 as feature was merged with master |
Revert/Undo a git merge that is not already pushed:
1 2 |
## Undo last merge commit git reset --hard HEAD~1 |
Note: 1 in HEAD~1 represent last commit. If any other commits happen in-between, use git reset –hard <merge_commit_sha> instead which you can get using git log command.
Check files in the master branch:
1 2 3 4 |
## Check file in master branch ls ## returns only file1 cd .. && rm -rf myrepo |