-
Notifications
You must be signed in to change notification settings - Fork 49
Undoing git missteps
Git does not have an explicit undo command. You must use different strategies to undo different changes.
Commits are snapshots of the repository’s state at specific times in a project’s history. When you undo changes in git, you generally return to an earlier commit, while saving the changes you made so you can deploy the changes somewhere else.
You can’t undo some of these undos. If you undo changes in the wrong way, you may lose some work. This is why it’s useful to save the changes that you want to undo, so you can fetch them if necessary.
Each scenario in this article contains a link to a worked undo example.
You made changes in wrong-branch
instead of your new_feature
branch, but you haven’t committed them.
-
in <wrong-branch>, store the changes in a stack:
git stash
This command removes the changes from
wrong-branch
. To verify, executegit status
. -
Checkout the feature branch where you want to move the changes:
git checkout <new-feature>
-
In <new-feature>, extract the stashed changes from the stack onto the correct branch:
git stash pop
See Uncommitted changes in main for an example.
First, be absolutely sure that you don’t want to save the changes.
To discard the changes without saving them, and restore main
, use git reset --hard
. Run git status
to confirm that the changes are deleted:
$ (main) git reset --hard HEAD HEAD is now at 6dc91a0 Merge pull request #141 from cbudz/aap-396 $ (main) git status On branch main nothing to commit, working tree clean
-
Repository branch structure
-
Forking workflow
-
git cherry-pick
-
List open pull requests