Shihui Guo

Watch Out When Undoing Things Under Git

Changing Last Commit

$ git commit --amend

Example:

$ git commit -m 'initial commit'
$ git add forgotten_file
$ git commit --amend

Unstaging a Staged File
Stage is an action which puts a file ready for putting into the repo (right after the add command). If you want to unstage a staged file, use:

$ git add .
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#       modified:   README.txt
#       modified:   benchmarks.rb
#
</pre>

Right below the “Changes to be committed” text, it says "use git reset HEAD ... to unstage". So, let’s use that advice to unstage the benchmarks.rb file:</p>

$ git reset HEAD benchmarks.rb
benchmarks.rb: locally modified
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#       modified:   README.txt
#
# Changes not staged for commit:
#   (use "git add ..." to update what will be committed)
#   (use "git checkout -- ..." to discard changes in working directory)
#
#       modified:   benchmarks.rb
#
</pre>

Abandoning your modifications since last commit
The same example used in Unstaging a Staged File, we want to abandon the modifications on benchmarks.rb, but keep the modifications on README.txt. simply do:

$ git checkout -- benchmarks.rb
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD ..." to unstage)
#
#       modified:   README.txt
#
</pre>

When you got multiple files to reset, go

git checkout -- .

Going back to previous commits
Sometimes, you wanna have a look of previous versions, but keep the current one. The first thing you need to do is to save, stage and commit modified files (don't worry if you are half-way of your work, use the amend command to fix the commit). Then you checkout previous commit:

git checkout hashID

Or checkout this commit as a new branch, this is useful because you can make changes on independent branch. If successful, you can merge the branch back, if not then simply abandon that branch. To checkout this commit as a new branch, do:

git checkout -b newbranchname hashID

Abandon Your Commits
When I say abandon, I mean throwing them away totally, and this is pretty dangerous and cant' be recovered. Be careful with this command:

git rebase -i hashID

Delete Your Branches
Delete your local branch

git branch -d the_local_branch

Delete remote branch

git push origin :the_remote_branch

点击查看评论