We use git for source code management at Rally. I keep a list of useful git commands on my personal Google site cheat sheet. I thought I’d share ten of my favorite commands with you:

#1
Scenario: I just wrote awesome code, have a local commit and want to push it (real good)
Solution: git push origin HEAD:branch-name
Explanation: you can push your local origin to the HEAD of any remote branch with this command

#2
Scenario: there is one local commit that I don’t want anymore.
Solution: git reset --hard HEAD~1
Explanation: HEAD~1 is a shorthand meaning “commit before the HEAD”. You can also use the SHA-1 of the hash you want to reset to

#3
Scenario: I have local code that I want to push to a new remote branch
Solution: git push origin HEAD:new-branch
Explanation: this will push your code and create the remote new-branch for you

#4
Scenario: I want to delete a remote branch
Solution: git push origin :branch-name
Explanation: this pushes “nothing” to branch-name and kills it. Note: you might still want to delete the local branch with git branch -d branch-name

#5
Scenario: I’ve made a bunch of local commits and want to squash them into a single commit before pushing them to a remote branch
Solution: git rebase -i branch-name (e.g. git rebase -i origin/master)
Explanation: this will start an interactive rebase by opening an editor with all your local commits that you can squash into a single commit. Follow the instructions in the editor which will tell you to “pick” and “s” commits

#6
Scenario: I want to checkout a remote branch and track it on a new branch on my machine
Solution: git checkout -b branch-name origin/branch-name
Explanation: this will create branch-name on my machine and track the remote one for changes

#7
Scenario: I really want a commit from somewhere else in the git repo on my branch
Solution: git cherry-pick sha-hex-number
Explanation: this will cherry pick the commit with the given SHA and merge it into my current branch

#8
Scenario: I want to quickly view a shorter version of the git log in a graph format
Solution: git log --oneline --graph
Explanation: this will show the one-line version of the log and draw an ASCII graph topology

#9
Scenario: Every time I do a pull the log shows a bunch of merges
Solution: git config --global branch.autosetuprebase always
Explanation: from now on all new branches will rebase rather than merge on a pull. To set this up for existing local branches do a git config branch..rebase true

#10
Scenario: there are a bunch of files and directories not being tracked by git and it keeps complaining at me
Solution: git clean -fd
Explanation: tell git to remove any untracked directories and files

#11 Bonus: I want to show commits that are one branch but not another because someone put extra commits into the release for this weekend and I want to punch them in the face for doing that: git log origin/master..origin/2011.08.06