Git Tips and Tricks

In retrospect, one of the hardest parts of developing a competency in programming for me was learning how to use git. I’m not kidding. The learning curve is pretty steep, and for the first six months or so of using git, it probably hindered me more than it helped me. In the beginning I would get myself into situations where I’d royally screw up a branch, an entire repo, or have no idea what I even screwed up so I’d just delete everything and re-clone. However, after a few years of battling with git, my git game has gotten pretty strong. It’s still a learning process, but here are some useful git commands I have in my config – some of them might be pretty obvious to you, but hopefully there are a couple you didn’t know about already.

git -
Checks out the last branch you were on. Insanely useful, yet maybe not obvious.

git log -p
You already know about git log, which will list the descriptions of your most recent commits. Adding “-p” will also print the diff for each commit.

git shortlog
Prints the commit descriptions in a concise, copy-and-pastable way to easily create changelogs or release announcements.

git for-each-ref –sort=-committerdate –count=10 –format=’%(refname:short)’ refs/heads/
My alias: “git recent”
This will print out the names of your 10 most recently used branches. If you are a branch hoarder like me and mortally fear deleting local branches (what if I need it one day?!), this can help you find what you’re looking for.

git commit –amend
My alias: “git amend”
This will allow you to re-write git history and amend the content and description of your last commit. It’s like a mini, easier interactive rebase for your last commit only. Simply make some changes, git add them, and do “git commit –amend” to smush the changes into the previous commit, and be given the chance to edit the description. Remember to “git push –force” afterwards if you’ve already pushed your branch to the remote, and never re-write history on branches that have been pulled by other people.

git reset
My alias: “git uncommit”
This will remove your most recent commit. However, it will keep your changes and return them to the working directory, so you can make changes and commit again. I use this sometimes when I’ve committed something, but then realize I wanted to get a different change in first – so I uncommit, stash, make the other change and commit it, then pop the first changes back on and commit again.

git reset –hard
My alias: “git clear”
Permanently discards any uncommitted changes. Use with caution – it’s usually best to just stash your changes in case you need them later, but if you really feel the need to kill your changes with fire, this will do the trick. If you append a specific commit hash to the end, you can discard uncommitted changes as well as any commits up until the one specified.