Undoing Changes

0

Undo latest commit using git revert HEAD
~/code/gitfaffing % git log --oneline
481db44 (HEAD -> master) crazy edit of world.txt
be880c6 added world.txt and edited hello.txt
aa1a9d2 init

~/code/gitfaffing % git revert HEAD
[master fda5598] Revert "crazy edit of world.txt"
 1 file changed, 1 insertion(+), 1 deletion(-)

~/code/gitfaffing % git log --oneline
fda5598 (HEAD -> master) Revert "crazy edit of world.txt"
481db44 crazy edit of world.txt
be880c6 added world.txt and edited hello.txt
aa1a9d2 init

Reverting this way just creates a new commit with the previous version. While this preserves history it is not minimal

To revert more than just one commit (3 commits in the example below)

git revert --no-commit HEAD~3..
git commit -m "the commit message"
Undo just one file from a previous commit using git checkout
git checkout be880c6 -- hello.txt
git commit -m 'file brought from previous time'
git push
Reset back to the previous version using git reset --hard <version>
~/code/gitfaffing % git log --oneline
fda5598 (HEAD -> master) Revert "crazy edit of world.txt"
481db44 crazy edit of world.txt
be880c6 added world.txt and edited hello.txt
aa1a9d2 init

~/code/gitfaffing % git reset --hard be880c6                              
HEAD is now at be880c6 added world.txt and edited hello.txt
sthapit@Air ~/code/gitfaffing % git log --oneline       
be880c6 (HEAD -> master) added world.txt and edited hello.txt
aa1a9d2 init

This is good for local changes but could create problems in a shared repository . For example if the shared repository has 481db44 crazy edit of world.txt and you reset it locally and then try to push the branch Git will throw an error because it thinks your local branch is not up to date. For shared repositories git revert is simpler even if the history is not as clean.

Amend latest commit using git commit --amend

This will just amend your latest commit. This is an easy option if you want to update your latest commit without reverting or removing the last commit.

~/code/gitfaffing % git log --oneline
481db44 (HEAD -> master) crazy edit of world.txt
be880c6 added world.txt and edited hello.txt
aa1a9d2 init

Edit world.txt to something better and then

~/code/gitfaffing % git add .
~/code/gitfaffing % git commit --amend
~/code/gitfaffing % git log --oneline 
e4ed093 (HEAD -> master) better edit of world.txt
be880c6 added world.txt and edited hello.txt
aa1a9d2 init
Undo uncommitted changes using git reset --hard HEAD
~/code/gitfaffing % git add .
~/code/gitfaffing % git reset --hard HEAD

  • 0 posts
  • 1 subtopic
  • 6 days ago by vince