In my master branch yesterday different people made their own commits. Last 2 commits are wrong, is there a way to checkout to master at an specific commit?
Something like
git checkout master -some_commit
In my master branch yesterday different people made their own commits. Last 2 commits are wrong, is there a way to checkout to master at an specific commit?
Something like
git checkout master -some_commit
Yes you can! You can directly go to any commit you like by passing the commit hash as an argument
git checkout COMMIT_HASH
You can find the commit hash by simply looking at the git log
.
Keep in mind that this will most likely leave you in a detached HEAD state.
Edit as per the discussion in the comments: what you can do is to go to your desired commit and from that detached HEAD state create a new branch. Go to your new branch and cherry-pick
the two wrong commits. At this point they are safe. You can safely revert back your master branch to the correct commit you want and then add the fixes you want. After all this, you are free to merge the other branch.
cherry-pick
the two commits in the new branchThe correct answer depends on what your ultimate goal is, and whether these commits also exist in a remote repository.
If all you want to do is see what the project looks like before those commits were applied, then
git checkout bad-commit-id^
This checks out a different "branch", and later you can checkout master
again.
If your goal is to change your repository such that those commits essentially no longer exist, you can do
git reset --hard bad-commit-id^
or
git revert bad-commit-id
The former erases all commits from bad-commit-id
to HEAD
. The latter just reverts the single bad commit by adding a new commit to HEAD
.
Which one you would choose largely depends on if the commits exist on a remote repository. Using reset
will cause problems when you try to push, either for you or for somebody else who has cloned the repository.
If it's a shared repository and you are a not-very-sophisticated git user, I would recommend using git revert
. If you know what you're doing, then git reset
also has its place, but you really do need to understand the ramifications of doing that.
tl;dr - git revert
is quite safe, while git reset
is a dangerous, but powerful tool.
You want git reset --hard HEAD~2
the HEAD~X
syntax refers to the commit X commits previous