My Favorite Git Commands and Tips

February 4, 2014

After I've been using any version control system for a while I tend to find myself having a go-to set of commands. This is especially true with git. These are commands I use all the time. Hopefully this will give you a idea of what you should be using that you're not already.

Interactive Rebase

Make a list of the commits which are about to be rebased. Let the user edit that list before rebasing. This mode can also be used to split commits.
This is it. Understanding how to use rebase, more specifically interactive rebase, is like looking into the soul of git. When you understand rebase for the first time you'll never think about version control the same again. Get this command down and you'll not only be insanely powerful at managing your source code, but you'll also realize you can work how you naturally want to work and be very efficient. Replace n with the number of revisions back from HEAD you want to work with.
git rebase -i HEAD~n

Patch Add

Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index.
Patch add is like pulling a rabbit out of your hat to non-git users. Want to know how you can have the same file both staged and unstaged at the same time? Just stage parts of changes to a file. Instead of just adding changes by whole files, this command walks you through all of the individual changes and asks if you want to stage them. Check out all the options it gives you because there are some handy ones. Make some changes and run the following.
git add -p

Get a File Version From Another Tree

This is something I find myself doing maybe too often. I think I tend to play too much. Anyhow, if you want to try out a version of a file that exists somewhere else, you can just check it out from that tree/branch.
git checkout BRANCH -- FILE_PATH

Pull With Rebase Instead of Merge

There are few workflows where you should have merge commits. In fact, even in those workflows where you explicitly want merge commits (like keeping a feature/release branch around), you still should avoid merge commits the rest of the time. However, the default operation of a pull is to do a merge. You can change this.

One time:

git pull --rebase

For a specific branch:

git config branch.master.rebase true


git config --global branch.autosetuprebase always

Work on Multiple Repositories with a Single Clone

In almost all other version control systems, they encourage you to scatter a billion copies of the same code all over your hard drive. Git does the opposite. Use git to manage all of your branches. In the same clone, add more remotes and fetch.
git remote add name some_other_url && git fetch name

Create New Branch

Create a new local branch right where you are.

git checkout -b my_branch

Related Posts