There are plenty of git cheatsheets on the web (Tower’s is my favorite), but many of them are lacking answers to the most common questions about workflow practices and dealing with mistakes. Here’s a list of some of the most commonly sought out answers to add to your personal cheatsheet.
Quick git add <all> options
Unstage files added with git add
1 2 3 4 5 | # Unstage all added files git reset #Unstage specific added file(s) git reset <file name> |
Undo the last commit
1 2 3 4 5 | # Keeps changes from that commit in the code git reset --soft HEAD~1 # Undoes changes from that commit in the code git reset --hard HEAD~1 |
Squash commits when merging a feature into the develop branch
1 2 3 | git checkout develop git merge --squash <feature branch> git commit |
Squash commits before merging using rebase
1 2 3 | # The number below reflects the number of commits back you want to review/alter. # Use git log to review past commits git rebase -i HEAD~4 |
In the text editor that comes up, replace the words “pick” with “squash” next to the commits you want to squash into the commit before it. Save and close the editor, and git will combine the “squash”ed commits with the one before it. Git will then give you the opportunity to change your commit message. To change your commit, comment out every line except the one with your new message.
Important: If you’ve already pushed commits to GitHub, and then squash them locally, you will have to force the push to your branch using git push -f
Helpful hint: You can always edit your last commit message, before pushing, by using: git commit --amend
Fixing a mistaken rebase
1 2 3 4 5 | # Displays an ordered list of the commits that HEAD has pointed to. It's basically an "undo" history for your repo git reflog # Identify the number associted with the commit before your bad rebase; sub it in below git reset HEAD@{2} |
Storing/moving uncommitted changes
1 2 3 4 | # If you're on the wrong branch and haven't yet commited git stash git checkout <correct branch> git stash apply |
Note: Alternatively to git stash apply , you can use git stash pop which works identically except it also throws away the (topmost, by default) stash after applying it (whereas git stash apply leaves it in the stash list for possible later reuse). This happens unless there are conflicts after git stash pop, in this case it will not remove the stash, behaving exactly like git stash apply. Another way to look at it: git stash pop is git stash apply && git stash drop .
Pull a remote branch not in the local repository
In versions of git 1.7.2.3 and higher you can simply type:
1 | git checkout <branch name> |
You should then see a message like:
1 2 | Branch <branch name> set up to track remote branch <branch name> from origin. Switched to a new branch '<branch name>' |
This is short for git checkout --track <remote>/<branch name> which is short for git checkout -b <branch name> <remote>/<branch name> .