Easy Version Control with Git

Easy Version Control with Git

Have you ever worked on a project that was so unwieldy, you were scared to update a file or add a feature? Maybe the problem was that you weren’t using a version control system. In today’s tutorial, we’ll learn the basics of what might possibly be the best VCS in the world: Git.

What is Git?

Git is a open-source code managemen tool; it was created by Linus Torvalds when he was building the Linux kernel. Because of those roots, it needed to be really fast; that it is, and easy to get the hang of as well. Git allows you to work on your code with the peace of mind that everything you do is reversible. It makes it easy to experiment with new ideas in a project and not worry about breaking anything. The Git Parable, by Tom Preston-Werner, is a great introduction to the terms and ideas behind Git.

Why Should I use Git?

You should definitely use a revision control system; as we already said, this gives you the freedom to do whatever you want with your code and not worry about breaking it. So if you’ve realized the benefits of using a revision control system, why should you use git? Why not SVN or Perforce or another one? To be honest, I haven’t studied the differences too closely; check out WhyGitIsBetterThanX.com for some helpful info.

How do I Get Set Up?

Git is pretty easy to get: on a Mac, it’s probably easiest to use the git-osx-installer. If you have MacPorts installed, you may want to get Git through it; you can find instructions on the GitHub help site. (And yes, we’ll talk about GitHub). On Windows, the simplest way to start rolling is to use the msysgit installer. However, if you’ve got Cygwin, you can git Git through there as well.

How do I use Git?

By now you should have Git installed; if you’re on a Mac, open up a terminal; if you’re on Windows open the Git Bash (from msysgit) or your Cygwin prompt. From here on, there shouldn’t be any OS differences.

Configuration

We’ll start by doing a bit of configuration. Every commit you make will have your name and email address to identify the ‘owner’ of the commit, so you should start by giving it those values. To do so, run these commands:

git config --global user.name "Your Name"
git config --global user.email "your@email.com"

It’s also nice to enable some text coloring, just for easier reading in the terminal.

git config --global color.diff auto
git config --global color.status auto
git config --global color.branch auto

git init

Now that Git knows who you are, let’s imagine we’re creating a simple PHP web app. (Of course, the bigger the project, the brighter Git shines, but we’re just learning the tools, right?) We’ve got an empty directory called ‘mySite.’ First focus on that directory (using the cd command). To get started with Git, you need to run the git init command; as you might guess, this initializes a Git repository in that folder, adding a .git folder within it. A repository is kind of like a code history book. It will hold all the past versions of your code, as well as the current one.

Git Init

Notice that your terminal path is appended with (master). That’s the branch you’re currently working on. Branch? Think of your project as a tree; you can create different features on different branches, and everything will stay separate and safe.

git add

We’ve started working on our application.

Files

Before we go any further, we should make our first commit. A commit is simply a pointer to a spot on your code history. Before we can do that, however, we need to move any files we want to be a part of this commit to the staging area. The staging area is a spot to hold files for your next commit; maybe you don’t want to commit all your current changes, so you put some in the staging area. We can do that by using the add command

git add .

The . simply means to add everything. You could be more specific if you wanted.

git add *.js
git add index.php

git commit

Now that we’ve staged our files, let’s commit them. This is done with the command

git commit

This takes all the files in our staging area and marks that code as a point in our project’s history. If you don’t add any options to the command above, you’ll get something like this.

vim

Each commit should have an accompanying message, so you know why that code was committed. This editor allows you to write your message, as well as see what is in this commit. From the image above, you can see that this commit is comprised of four new files. The editor you’re using to write the message is Vim; if you’re not familiar with vim, know that you’ll need to press i (for Insert) before you can type your message. In the shot above, I’ve added the message “Initial Commit.” After you write your message, hit escape and type :wq (to save and exit). You’ll then see you’re commit take place.

Commit Aftermath

You can use a few options to make commits more quickly. Firstly, -m allows you to add your message in-line.

git commit -m "initial commit"

Then, -a allows you to skip the staging area; well, not really. Git will automatically stage and commit all modified files when you use this option. (remember, it won’t add any new files). Together, you could use these commands like this:

git commit -am 'update to index.php'

So how does Git tell commits apart? Instead of numbering them, Git uses the code contents of the commit to create a 40 character SHA1 hash. The neat part about this is that, since it’s using the code to create the hash, no two hashes in your project will be the same unless the code in the commits is identical.

git status

The git status command allows you to see the current state of your code. We’ve just done a commit, so git status will show us that there’s nothing new.

status, clean

If we continue working on our imaginary project, you’ll see that our status changes. I’m going to edit our index.php and add another file. Now, running git status gives us this:

Status, not clean

The update is divided into two categories: “changed but not updated,” and “untracked files.” If we run

git add userAuthentication.php
git status

you’ll see that we now have a “changes to be committed” section. This lists files added to the staging area. I’m going to commit these changes with this:

git commit -am 'user authentication code added'

Now running git status shows us a clean working directory.

git branch / git checkout

Here’s a scenario: we’re working happily on our project when suddenly we have a grand idea. This idea is so revolutionary, it will change our project drastically. We’ve got to give it a try, but we don’t want to throw this insecure, first-draft code in with our tested and true code. What to do? This is where git branch will be immensely helpful. Let’s branch our project so that if our big idea doesn’t work out, there’s no harm done.

git branch

Just running the branch command sans options will list our branches; right now, we’ve only got the master branch, which is what any git repository starts with. To actually create a new branch, add the name of your new branch after the command.

git branch bigIdea

When you create a new branch, you aren’t switched to it automatically. Notice that our terminal still says (master). This is where we use branches comrade command git checkout.

git checkout bigIdea
Git Branch

(Tip: you can create a branch and switch to it in one fell swoop with this command: git checkout -b branch name.) As you can see, we’re now on the bigIdea branch. Let’s code up a storm. Git status will show our work.

2 new files

Let’s commit our changes:

git add .
git commit -m 'The Kiler Feature added'

All right, enough of this feature for now; let’s go back to our master branch; but before we do, I want to show you our current project folder.

Files, branch bigIdea

Now, switch back to the master branch; you know how:git checkout master. Look at our project folder again.

Files, branch master

No, I didn’t do anything; those two files are only part of the bigIdea branch, so we don’t even know they exist from the master branch. This not only works for complete files, but also for even the smallest changes within files.

git merge

Ok, so we’ve been working hard on that bigIdea branch in our spare time. In fact, after another commit, it’s looking so sweet we’ve decided it’s good enough to join the master branch. So how do we do it?

The git merge command is made for exactly this purpose. While on the master branch, give this a try:

git merge bigIdea

It’s that easy; now, everything on the bigIdea branch is a part of the master branch. You can get rid of the bigIdea branch now, if you want.

git branch -d bigIdea

I should mention that if you haven’t merged a branch, Git won’t let you delete it with this command; you’ll need to use an uppercase D in the option. This is just a safety measure.

git log / gitk

You’ll probably want to look at your commit history at some point during your project. This can easily be done with the log command.

git log

This will output a list of all the commits you’ve made in a project, showing them in reverse order. You can get at quite a tidy chunk of info here:

  • the commit author
  • the commit hash
  • the date and time
  • the message
git log

Definitely informative, but rather dry, no? We can brighten things a bit with the graph option.

git log --graph
git log --graph

Now we can see the tree structure, sort of. Although we don’t get their names, we can see each of the branches and which commits were made on them. If you’re used to working in a terminal, you might be fine with this. However, if (previous to this experience) the word terminal strikes you first as something deadly, breathe easy: there’s an app for that. Try this:

gitk --all
gitk

This is the graphical repository browser. You can browse around your commits, see exactly what was changed in each file during a commit, and so much more. (You’ll notice I added a few commits before merging, just to make the tree structure more recognizable.)

GitHub

Now that you’ve got a reasonable knowledge of Git under your belt, let’s look at some of the collaborative parts of Git. Git is a great way to share code with others and work on projects together. There are a number of Git repository hosting sites. We’ll just look at one: GitHub.

GitHub Home Page
GitHub Sign Up

Head over to the GitHub sign-up page and create an account. You’ll need an SSH public key, so let’s create that right now! (Note: you don’t need the key while signing up; you can add it later.)

Open up your terminal and type this:

ssh-keygen -t rsa -C "your@email.com"
ssh

The t option assigns a type, and the C option adds a comment, traditionally your email address. You’ll then be asked where to save the key; just hitting enter will do (that saves the file to the default location). Then, enter a pass-phrase, twice. Now you have a key; let’s give it to GitHub.

First, get your key from the file; the terminal will have told you where the key was stored; open the file, copy the key (be careful not to add any newlines or white-space). Open your GitHub account page, scroll to SSH Public Keys, and click “Add another public key.” Paste in your key and save it. You’re good to go! You can test your authentication by running this:

ssh git@github.com

You’ll be prompted for your pass-phrase; to avoid having to type this every time you connect to GitHub, you can automate this. I could tell you how to do this, but I’d probably inadvertently plagiarize: the GitHub Help has a plain-english article on how to do it.

Git Clone

So now you’re set up with GitHub; let’s grab a project. How about jQuery? If you go to the jQuery GitHub project, you’ll find the git clone URL. Run this:

git clone git://github.com/jquery/jquery.git
git clone

This creates a jquery folder and copies the whole jquery repository to your computer. Now you have a complete history of the project; check it out with gitk –all.

git push

So let’s say you’ve been working on a project, managing it with git locally. Now you want to share it with a friend, or the world. Log into GitHub and create a new repository. GitHub will give you a public clone URL (for others wanting to download your project) and a personal clone URL (for yourself).

Create New Repository

Then, come back to your project in the terminal and give this a whirl:

git remote add origin git@github.com:andrew8088/Shazam.git

A remote is a project repository in a remote location. In this case, we’re giving this remote a name of origin, and handing it our private clone URL. (Obviously, you will have to substitute my URL for your own.) Now that the project knows where it’s going . . .

git push origin master
Git push

This pushes the master branch to the origin remote. Now you’re project is available to the world! Head back to your project page and see your project.

GitHub Project

git pull

You might be on the other end of a project: you’re a contributor instead of the owner. When the owner pushes a new commit to the repository, you can use git pull to get the updates. Git pull is actually a combo tool: it runs git fetch (getting the changes) and git merge (merging them with your current copy).

git pull

You’re Set!

Well, there’s so much more you can learn about Git; hopefully you’ve learned enough commands to help you manage your next project more smartly. But don’t stop here; check out these resources to become a Git master!


Tags: git
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.quizzpot.com Crysfel

    well done!! this is really good, everyone should use a control version system, i’m going to try thisone in my linux server.

    Thanks for the tut

  • damith chathuranga

    Nice Article!!!!!

  • http://codesanity.net trs21219

    Nice man. Passing this to my colleagues as we will be moving from svn to git very soon and they needed a better way to understand it!

  • Lars

    Needed this a couple of months ago. I think this is a great thing for guys who want to start with version control but don’t know the ins and outs

  • http://michael.theirwinfamily.net Michael

    Great article! Version control can be a little daunting at first, but I agree… every developer should use some sort of version control.

    Thanks!

  • http://twitter.com/neagaoleg neagaoleg

    i’ve started to you use git a few months ago, it was realy easy. thanks for details in this post

  • http://www.000webhost.com/205252.html Hamza Oza

    Cool tut. Very detailed.

  • http://www.milesj.me/ Miles Johnson

    The msysgit CLI is just terrible. Would be nice to get an article about integrating Putty with GIT/Githb.

    However very nice article, will probably dive into GIT again.

    • Robert

      Ehm.. INTEGRATING putty? That’s pretty weird you do not need an whole article to know how to “integrate” putty… It takes about 2 seconds.

  • Matthew

    This is great, been looking for some more insight into this. Thanks alot!

  • http://ethan.luffle.com Ethan

    Hey, thanks. You should probably go over GitHub-specific commands, as that is the most popular Git hosting service.

  • http://www.jennieroutley.co.uk Jen

    Yey! I use GIT already, It is awesome when working on projects with others around the globe.

  • http://monkey-house.ca Greg

    I’m so accustomed to the GUI tools provided by Tortoise + CVS that I can’t imagine moving to command-line administration of my version control.

    Quick web search turns up this project:

    http://code.google.com/p/tortoisegit/

    Might make Git a viable option for my “set in my ways” attitude. ;-)

    • http://monkey-house.ca Greg

      D’oh, I didn’t read super-carefully… the above link might not be what I thought it was… I’ll have to read it when I can actually pay attention.

    • http://andrewburgess.posterous.com Andrew Burgess
      Author

      The msysgit install comes with a Git GUI; honestly, I haven’t done too much with it, but it is there. Or, you might want to check out Git Extensions:

      http://code.google.com/p/gitextensions/

    • http://www.curtismchale.ca curtismchale

      there are a bunch of git gui’s out there. I use Gitx on my mac personally. Though I mostly just use it for browsing for a specific change. the command line is way faster to work in.

  • Ali Baba

    Nice article. However Git commands same as SVN. If you using SVN i don’t see point switching plus SVN has better standard and more plugins and addons

    • http://tuntis.net tuntis

      Git provides a much more flexible decentralized workflow, and the branching system makes working in teams (and also alone) much easier.

      It’s faster than SVN, too.

      One should also take a look at Mercurial and Bazaar.

  • http://www.crucialwebhost.com Kyle Anderson

    Great article, especially since we’ve opted to switch from SVN to Git on our servers since SVN creates so many empty .svn directories, while Git doesn’t.

    By the way, you have a spelling error in the first sentence:

    “Git is a open-source code managemen tool”

    Should be “management” :-)

  • http://twitter.com/aziz_light Aziz Light

    Nice work! We’re getting some very interesting articles on Nettuts lately :)
    Thanks a lot for this tutorial.

  • http://minichiello.name Gerson Minichiello

    Great stuff, Thanks

  • http://fwebde.com/ Eric B.

    Excellent post! I’ve been looking for a way to get started with version control, with Git.

  • Desu

    I haven’t heard about Git. But now I want to try it. Thanks for your post.

  • http://twitter.com/cyaconi Carlos

    Great article, but I still have a doubt. How do you manage the synchronization of changes, when there is a team working in a project?
    Think the case in which 2 programmers are working in the same branch, and they want to push their changes to the remote repository, What if there are conflicts on the commited/pushed files? What is the best way, using command line, to solve those conflicts?.
    I’m used to work with eclipse/CVS which has a powerful visual “merger”, that’s why I can’t imaging how to solve it with the command line only.

    Great tutorial for a newbie (as me)
    Thank you!

  • http://www.brandonmartinez.com Brandon Martinez

    I love Git! Using it in conjunction with Capistrano is awesome (even for non-rails projects). For example, I use it as my WordPress 1-click deployment versioning and publishing system. Check it out:

    http://www.brandonmartinez.com/2009/08/17/git-capistrano-ssh-and-wordpress-an-awesome-combination/

  • http://www.coreguardian.org Luke Chadwick

    I’m a big fan of Git! It’s not hard to fall in love with the features. In particular the ability to use SVN as a part of your Git workflow. I’m still waiting for an integration with Eclipse that doesn’t suck, but now that egit/jgit is being run out of eclipse.org it is only a matter of time.

  • http://11heavens.com/ Caroline Schnapp

    Excellent article, thank you!

  • http://asimilatorul.com/adapter/post/git-resources/ alexandrul

    added to my git resources list.

  • zmey

    Best tutorial on git I have read. Just the right amount of information for me. Thank you

  • http://www.what-a-geek.com Adit Gupta

    Excellent post!! :)

  • http://webski.com.au Zoran

    Yeap git is really powerful. Thanks for the tutorial.

  • Ollie

    Awesome, I was always looking for this kind of tut… Thanks! :)

  • http://www.ademaweb.nl Jeroen

    is there no graphic interface client for OSX? If not, is there a free alternative which does? I’m not fan of the terminal. tnx in advance!

    • http://andrewburgess.posterous.com Andrew Burgess
      Author

      curtismchale (comment above) mentioned gitx for Mac.

  • Joe

    Just installed git on my mac, but I use hg at work. Git seems nice but this article makes me want to use it more now :D

  • http://www.massbase.com/enatom enatom

    Is there a GIT (gui) version for Ubuntu ?

  • http://inspiredbywordpress.co.uk Daniel Groves

    Cool, sure, but I don’t know if this is for me. It’s the sort of thing that looks all good and that, but to me I just feel a little… cautious about it.

  • sn11121111

    I don’t see why would one use prompt and type things there, when we have svn with all kind of GUIs and even VS plugins etc?
    Am I missing something?

  • http://www.demogeek.com DemoGeek

    Finally you’ve gotten me into Git. It was a long due that I move to this but this explained it pretty clear and got me convinced. Thank you!

    Just a suggestion, may be a bit more detailed article on GitHub would complete this article series. Just a thought.

  • Sam

    Best Git tutorial I’ve seen; the Git manual I was looking for. Thank you!

  • http://superfancy.net Stevie Benge

    Yes I agree this is an excellent article to get you started with Git. Much appreciated, thank you.

    I chose to build Git from source following these awesome instructions:
    http://hivelogic.com/articles/compiling-git-on-snow-leopard/

  • Ryan

    Thanks for the article, I have never used version control (or known specifically what some benefits are) until i read this.

  • http://twitter.com/mcaulay mcaulay

    Good introductory article I thought. One thing which may trip new users up though is your section on ssh keys, when you generate the key, 2 files are created. The contents of the “id_rsa.pub” file are what you need to paste into the github interface. The other file is the private key and shouldn’t be shared.

  • http://bwebi.com barat

    Nice :) I was thinkig about some kind of version control. I don’t realy need it now, but it’s something what can help me in my future work (we have 2 or 3 portals to re-code in my company) :) I’ll practice this on my page redesign/re-code/re-all :)

  • Nazar

    Why go through the pain of msysgit through cmd.exe when a much better (and saner) experience can be had using Cygwin + Putty

  • http://www.racinewebworks.com Jesse

    Thanks for the intro, a little more detailed than Carsonified’s Subversion for Designers. Check out Beanstalk if you like SVN too.

  • http://harrymahardhika.com Harry M

    Nice post, thanks

  • http://www.clubedosnerds.com.br Alberto Marlboro

    Nice tuto, I used SVN sometime ago, but I prefer Git, looks simple.

    I start reading and to share with no english speaking people I did a portuguese version (http://www.clubedosnerds.com.br), with my own images and with my words, but following the same path.

  • http://www.mauriciorivera.cl Mauricio Rivera

    Thanks! I wanted to learn how to use Git, but I didn’t have the time to do it. With this tutorial there’s no escuse to begin using it right now.

  • http://www.utilitiessavings.co.uk Drew Spencer

    Been looking for something like this for a while – excellent.

  • http://tanish.trixsolution.com/ Tanish

    Thanks for the article, U’ve finally got me into Version Control which I was missing for some times. I know I could have done things much better with a version control system. I was doing version controlling manually which was kinda lame comparing with GIT. Once again, thank you for getting me into GIT and GITHUB.

  • awake

    below URL should give you a better understanding of what versioning is and it’s importance if you’re somewhat new to the term.

    http://betterexplained.com/articles/a-visual-guide-to-version-control/

  • http://diegoripley.com Diego R

    Nice article. I’ve been using Git for about a week now and it’s pretty awesome.

  • http://ulfklose.de/anleitung-zum-aufsetzen-von-git-und-trac-unte Ulf

    Git (and GitHub) rock. But I’m lucky as hell, that I don’t need to work with Windows. The screenshots look awful. Who can work that way? Still no native Windows version of all the Git tools available?

    I’m using Git for several months now on several projects and the problems I had were much smaller than the one’s I used to have when using Subversion. I really love Git. It’s fast, unobtrusive (I’m a command-liner, I confess) and elegant. Runs on my server flawlessly. If anyone wants to setup his own Git server (and speaks German), click on my name, I’ve written a tutorial how to setup such a machine.

  • http://evansofts.com Evan-XG

    very nice tutorial . I have follow it and actually it is nice and amazing .
    from now on I won’t be duplicating my project folder to my external drive to be safe of potential changes .

  • http://evansofts.com Evan-XG

    HI there I am very curious and found that : rm -rf .git

    you did not talk about removing the repository