This is the aggregation of my daily used Git commands. I will continue adding them as I find other useful ones.
1. Discard local file modifications
# discard specific file
git checkout -- <file_path># discard all unstaged change
git checkout -- .# discard unstaged changes since <commit>.
git checkout <commit>
2. Undo local commits
# discard staged and unstaged changes since the most recent commit.
git reset HEAD~1
git reset --hard HEAD~13. Edit a commit message
# add your staged changes to the most recent commit
git commit --amend
git commit --amend -m "New message"4. Delete local branch
git branch -d branchname
git branch -D branchname5. Delete remote branch
git push --delete origin branchname
git push origin :branchname6. Reverting pushed commits
# reverts the commit with the specified id
git revert c761f5c
# reverts the second to last commit
git revert HEAD^
# reverts a whole range of commits
git revert develop~4..develop~2
# undo the last commit, but don't create a revert commit
git revert --no-commit HEAD = git revert -n HEAD7. Avoid repeated merge conflicts
git config --global rerere.enabled true8. Find the commit that broke something after a merge
Tracking down the commit that introduced a bug after a big merge can be quite time-consuming. Luckily git offers a great binary search facility in the form of git-bisect. First you have to perform the initial setup:
# starts the bisecting session
git bisect start# marks the current revision as bad
git bisect bad# marks the last known good revision
git bisect good revision
After this, Git will automatically check out a revision halfway between the known “good” and “bad” versions. You can now run your specs again and mark the commit as “good” or “bad” accordingly.
# or git bisec bad
git bisect goodThis process continues until you get to the commit that introduced the bug.
9. Filter branch
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch secrets.txt' \
--prune-empty --tag-name-filter cat -- --allThis will remove the file secrets.txt from every branch and tag. It will also remove any commits that would be empty as a result of the above operation.
10. Show commit history
git log # show log
git log --oneline # show log in one line
git log -n1 # show log of last commit
git log -p <file_name> # show log for a file11. Show configuration list
git config --list # see all setting of your git
git config --local --list # see only local setting
git config --global --list # see only global setting12. Unset configuration
git config --unset key
git config --unset --global key13. See all file changes locally
git diff
git diff <file_name> # Show changes for only one file14. For each change to file_name, see who made the change and the time that it happened
git blame <file_name>15. Show a log of changes to the local repository’s HEAD
git reflogHappy Gitting~
