DEV Community

loading...
Cover image for Git and GitHub Essentials - #7 Undoing

Git and GitHub Essentials - #7 Undoing

envoy_ profile image Envoy-VC ・2 min read

📌Section 1.1: Return to a previous commit

To jump back to a previous commit, first find the commit's hash using git log.

To temporarily jump back to that commit, detach your head with:

git checkout 789abcd
Enter fullscreen mode Exit fullscreen mode

This places you at commit 789abcd. You can now make new commits on top of this old commit without affecting the
branch your head is on. Any changes can be made into a proper branch using either branch or checkout -b.

To roll back to a previous commit while keeping the changes:

git reset --soft 789abcd
Enter fullscreen mode Exit fullscreen mode

To roll back the last commit:

git reset --soft HEAD~
Enter fullscreen mode Exit fullscreen mode

To permanently discard any changes made after a specific commit, use:

git reset --hard 789abcd
Enter fullscreen mode Exit fullscreen mode

To permanently discard any changes made after the last commit:

git reset --hard HEAD~
Enter fullscreen mode Exit fullscreen mode

📌Section 1.2: Undoing changes

Undo changes to a file or directory in the working copy.

git checkout -- file.txt
Enter fullscreen mode Exit fullscreen mode

To only undo parts of the changes use --patch. You will be asked, for each change, if it should be undone or not.

git checkout --patch -- dir
Enter fullscreen mode Exit fullscreen mode

To undo changes added to the index.

git reset --hard
Enter fullscreen mode Exit fullscreen mode

Without the --hard flag this will do a soft reset

📌Section 1.3: Revert some existing commits

Use git revert to revert existing commits, especially when those commits have been pushed to a remote repository.
It records some new commits to reverse the effect of some earlier commits, which you can push safely without
rewriting history.

Don't use git push --force unless you wish to bring down the opprobrium of all other users of that repository.
Never rewrite public history.

If, for example, you've just pushed up a commit that contains a bug and you need to back it out, do the following:

git revert HEAD~1
git push
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide