Git is a fantastic technology that not only provides historical tracking of source code throughout development, but also enables multiple developers to work on the same project without stepping on each others feet.
I wanted to create a sort of cheat sheet for git commands that I find myself using often. I will continue to update this post as I discover other handy git commands.
git checkout -b <branch>
git checkout -- <file>
git branch -m <oldName> <newName>
git merge <branch>
git add -A
stage all new, modified or removed files to the working tree. Note this is different to
git add . which only stages new and existing files.
git diff HEAD
The same as
git diff but reviews all changes rather than just those unstaged.
git rm --cached <filename>
Very useful when you have files you don't want tracked that you forgot to specify in
.gitignore that have previously committed. After adding them to .gitignore run this command to ensure they are removed from the repo without deleting them from your local project directory.
git reset --hard
DANGER - exercise caution when using this command as it has the potential to throw away hours of work.
I often find I have uncommitted changes in a branch I've been messing around in (whitespace, print statements) git doesn't let you checkout another branch with uncommitted changes so this is a quick way to reset your project directory to the HEAD.
git reset --hard HEAD^
We've all made commits we immediately regret... Use this command to destroy the changes from the last commit.
git commit --amend -m <newMsg>
-m option allows you modify the previous commit message. You can also stage new changes to the commit and the previous commit will inherit them.
git branch --merged | egrep -v "(^\*|master|main|<branchToSave>)" | xargs git branch -d
DANGER - this will delete any newly created branches that have not yet been pushed to the remote repo. be sure to specify special cases as in
This can be used to clean up your local repository if you have lots of old branches that have since been merged. If you want to learn how this works see this great stack overflow post.