How To Revert the Last git Commit

shell$ git log | head -1 commit a203e1bd04718bff10a3df4a3389c493c97c0432 Use the commit string as the last argument to the git revert command: shell$ git revert -m 1 a203e1bd04718bff10a3df4a3389c493c97c0432
![]() |
shell$ git log | head -1 commit a203e1bd04718bff10a3df4a3389c493c97c0432 Use the commit string as the last argument to the git revert command: shell$ git revert -m 1 a203e1bd04718bff10a3df4a3389c493c97c0432
Show commits and messages that match
1 |
git log --all --grep='SEARCH_STRING_HERE' |
Include code diffs
1 |
git log --all --grep='SEARCH_STRING_HERE' -p |
Include file names
1 |
git log --all --grep='SEARCH_STRING_HERE' --name-only |
First, get on the branch that you know already has the commits you are looking for:
1 |
git checkout theBranch-1234 |
Copy-and-paste the commit(s) you want:
1 |
git log |
~or~
1 |
git log -p |
Optionally, display the code changes for a visual confirmation:
1 |
git show {one or more commit ID's} |
Finally, extract the list of branches that contain the desired commits:
1 2 |
git branch --contains CommitID-A git branch --contains CommitID-B |
Example:
1 2 3 |
git log git branch --contains 097e1859f248a7aa5e148a2a946be3e360030095 git branch --contains 24339549f9f1920a33f721d3faa2538c8ba5d249 |
Quickref: How to Remove a file from the staging area
1 |
git rm --cached {fileName(s)} |
The Story Recently, I accidentally added some files to git’s pre-commit phase, i.e.:
1 2 3 4 5 6 7 8 9 10 11 12 |
shell> git status On branch master Your branch is up-to-date with 'origin/master'. Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: good1.xml new file: good2.xml new file: bad1.xml new file: bad2.xml modified: good3.xml modified: bad3.xml |
For example, here is how to handle the above situation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
shell> git rm --cached bad1.xml bad2.xml bad3.xml shell> git status On branch master Your branch is up-to-date with 'origin/master'. Changes to be committed: (use "git reset HEAD <file>..." to unstage) new file: good1.xml new file: good2.xml modified: good3.xml Untracked files: (use "git add <file>..." to include in what will be committed) bad1.xml bad2.xml bad3.xml |
To better understand, here are the phases/states/stages that git uses: Untracked – when a file is first created, git […]
1 2 3 |
git log {path_and_file} git checkout {commit_hash} -- {path_and_file} git checkout 8c7eae3f518bb7fd98eb6e8344270f02065d83ee -- myFile.txt |
~or~
1 |
git checkout master -- theSubDir/theFile.json |