Git and GitHub Tutorial – Version Control for Beginners

Are you a new developer looking to level up your skills? One fundamental tool you‘ll need to master is version control. Version control allows you to track changes to your code over time, collaborate with other developers, and confidently experiment without fear of losing your work.

While there are several version control systems available, Git has emerged as the most popular choice for developers today. In this tutorial, we‘ll introduce you to the key concepts of Git and show you how to host your Git projects on GitHub to share with the world.

By the end of this tutorial, you‘ll know how to:

  • Set up Git on your local machine
  • Create a Git repository and track file changes
  • Create and merge branches to work on features separately
  • View your repository‘s history and undo accidental changes
  • Host your code on GitHub and clone remote repositories
  • Collaborate with others using pull requests

We‘ll assume you‘re completely new to Git and version control, so don‘t worry if you‘ve never used them before. And while we‘ll focus on using Git via command line, most of the concepts you‘ll learn apply to using Git through visual tools as well.

Let‘s get started!

What is Version Control?

Version control is a system that lets you manage and track changes to files over time. It‘s like having an unlimited "undo" button for your project. With version control, you can:

  • View the history of changes to your files
  • See who made each change and when
  • Revert files back to a previous state
  • Create separate versions of files to experiment with new features
  • Merge versions together

Without version control, you‘ve likely relied on saving multiple versions of a file, like "report-final.doc", "report-final-revised.doc", "report-final-revised-2.doc". It‘s easy to lose track of which version is the latest, and you run the risk of accidentally overwriting or deleting files.

Version control systems solve these problems by maintaining a single source of truth for your project and tracking each change you make.

There are two main types of version control systems:

  1. Centralized Version Control Systems (CVCS) – A central server stores all versions of the files. Developers "check out" files to make changes and then "check in" the latest changes back to the server. CVS and Subversion are examples of centralized systems.

  2. Distributed Version Control Systems (DVCS) – Every developer has a complete copy of the repository on their local machine, including the full version history. Changes can be synced between repositories as needed. Git and Mercurial are distributed systems.

Distributed version control like Git is the most popular choice for modern software development due to its flexibility, performance, and offline access. So let‘s dive into Git!

Introduction to Git

Git is a distributed version control system developed by Linus Torvalds in 2005. Some key features that have made Git so popular include:

  • Performance – Git performs most operations locally, making it very fast compared to centralized systems that rely on a server.
  • Branching – Git makes it easy to create isolated environments for experimenting with changes through its lightweight branching model.
  • Distributed – Each Git directory on every computer contains a complete copy of the repository with its full history, allowing offline work and flexible collaboration workflows.
  • Open Source – Git is released under the GPL open source license and has a large community supporting its ongoing development.

To understand how Git works, let‘s cover some key terminology:

  • Repository – A collection of files and their version history. Also known as a "repo".
  • Commit – A snapshot of changes made to the repo at a particular point in time. Each commit has a unique ID.
  • Branch – An independent line of development within the repo. The default branch is usually named "main" or "master".
  • Staging – Marking changes to files to include them in the next commit.
  • HEAD – A reference to the current branch or commit you‘re working with in the repo.

Setting Up Git

To use Git on your machine, you‘ll first need to install it. The process for installing Git varies by operating system:

  • Windows – Download and run the installer from the official Git website: https://git-scm.com/download/win
  • Mac – Use the Homebrew package manager with brew install git or download the installer from https://git-scm.com/download/mac
  • Linux – Use the built-in package manager for your distribution, like apt-get install git on Debian/Ubuntu or yum install git on Fedora.

After installing, open a terminal and check that Git is available by running:

git --version

You should see the installed version of Git printed out, like:

git version 2.31.1

Next, configure Git with your name and email address. This information will be attached to the commits you make. Run the following commands, replacing the values with your own:

git config --global user.name "Your Name"
git config --global user.email [email protected]

Optionally, you can configure your default Git text editor, like:

git config --global core.editor nano

Now you‘re ready to start using Git!

Creating Your First Git Repository

Let‘s walk through initializing a Git repository, committing changes, and viewing the repo history.

First, create a new directory for your project and navigate into it:

mkdir my-project
cd my-project

Then initialize a new Git repository in the current directory with:

git init

You‘ll see output like:

Initialized empty Git repository in /path/to/my-project/.git/

Git has created a hidden ".git" directory to store the repo metadata. You won‘t need to directly edit anything in this directory.

Next, let‘s create a file to track in our repo:

echo "# My Project" > README.md

The git status command shows the current state of the repository, like any uncommitted changes. Run it now and you‘ll see:

On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        README.md

nothing added to commit but untracked files present (use "git add" to track)

Git sees that we‘ve added a new file called README.md but it‘s currently "untracked", meaning Git isn‘t yet tracking changes to it.

To start tracking the file and stage it to be included in the next commit, use git add:

git add README.md

Now git status will show:

On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   README.md

Our README.md file is now staged. Let‘s commit it with a message describing the changes:

git commit -m "Add README file"

You‘ll see output like:

[master (root-commit) 3c9c96f] Add README file
 1 file changed, 1 insertion(+)
 create mode 100644 README.md

The -m flag lets us pass a commit message directly via the command line. If we left it off, Git would open our default text editor to prompt us for a message.

Congratulations, you‘ve made your first Git commit! We can see it in the commit history by running:

git log

Which shows:

commit 3c9c96f3b8d9e8d70169c1bd6f9f50c5681e8a43 (HEAD -> master)
Author: Your Name <[email protected]> 
Date:   Thu Apr 29 09:30:32 2021 -0400

    Add README file

Each commit is identified by a unique 40 character SHA-1 hash. The (HEAD -> master) indicates that our HEAD, or current working version of the repo, is pointing to the latest commit on the master branch.

As we continue to make changes, we can always review the differences between the latest changes and the previous commit with git diff.

Branching and Merging

One of Git‘s most powerful features is its branching model. A branch represents an independent line of development. By default, your repo starts on the master branch (sometimes called main if you created a new repo recently).

You can create new branches to experiment with different versions of your project without affecting the main version. Then you can merge a branch back into master when you‘re ready to incorporate the changes.

Let‘s see branching in practice. Say you want to redesign your project‘s interface in a new ui-redesign branch. Create the branch and check it out with:

git branch ui-redesign
git checkout ui-redesign

Or create and switch to it in a single command with:

git checkout -b ui-redesign

Now any commits you make are added to the ui-redesign branch, not master. Let‘s edit the README file:

echo "## Interface Design" >> README.md 

Stage and commit the change:

git add README.md
git commit -m "Add interface design section to README"

You can switch back to the master branch at any time with:

git checkout master

Notice your README file has reverted to the original version without the new "Interface Design" section. That change is isolated to the ui-redesign branch.

After experimenting in ui-redesign, you decide you like the changes and want to merge them into master. First switch back to master:

git checkout master

Then merge the ui-redesign branch into master with:

git merge ui-redesign

You‘ll see output like:

Updating 3c9c96f..7d2bc9d
Fast-forward
 README.md | 1 +
 1 file changed, 1 insertion(+)

The README file in master now has the "Interface Design" section added. You can continue developing in master or delete the ui-redesign branch if you no longer need it:

git branch -d ui-redesign

This only scratches the surface of what‘s possible with Git branches – you can have multiple long-running branches, branches that track remote repositories, use branches to manage releases, and more! Branches are a key part of using Git effectively.

Collaborating with GitHub

So far we‘ve seen how to use Git locally to manage versions of your project. Next let‘s see how to share your Git repo and collaborate with others using GitHub.

GitHub is a web-based hosting service for Git repositories. It provides a central place to store your code and let‘s other developers access and contribute to your projects. It also adds features like issue tracking, pull requests, and continuous integration on top of Git.

To get started, create a free account on GitHub: https://github.com/join

After verifying your email address, click the "+" icon in the top right to create a new repository. Give it a name, choose whether to make the repo public or private, and click "Create repository".

On the next screen, GitHub shows instructions for pushing an existing local repository. Since we already have a local repo, run the following commands (replacing "username" and "reponame" with your GitHub username and repository name):

git remote add origin https://github.com/username/reponame.git
git branch -M main 
git push -u origin main

This tells Git that you want to add a remote repository with the alias "origin" at the specified GitHub URL, switches your local branch name to "main", and then pushes your latest commits to the remote repo.

Refresh the GitHub page and you‘ll see your README file displayed! You can now share the URL with others or continue making changes locally and pushing them to GitHub.

To collaborate with others on GitHub, you‘ll typically follow a process like:

  1. Create a fork of the original repository in your own GitHub account
  2. Clone your fork to your local machine with git clone
  3. Create a new branch for your changes
  4. Commit changes to your branch
  5. Push your branch to your forked repo on GitHub
  6. Open a pull request asking to merge your changes into the original repo

This allows the maintainer of the original project to review your changes before merging them. It‘s a common workflow for contributing to open source projects on GitHub.

There‘s much more to cover with Git and GitHub, but these basics will get you started! As you use them on your own projects, you‘ll encounter more advanced concepts like resolving merge conflicts, interactive rebasing, and GitHub issues and project boards.

Additional Git Tips and Resources

Some quick tips for using Git effectively:

  • Commit often and write descriptive but concise commit messages. A good format is: <type>: <subject> where type is feat, fix, docs, etc. and subject is an imperative phrase.
  • Use branches extensively to keep work-in-progress separated from stable versions.
  • Agree on a branching strategy with your team, like GitHub flow.
  • Learn to rebase and squash commits to keep your history tidy.
  • Back up your repos to a remote like GitHub.

And some resources to go further with Git:

You now have a solid understanding of how Git and GitHub can help you version and collaborate on your projects. Start incorporating them into your development workflow and you‘ll wonder how you ever worked without them! The best way to get comfortable is to use Git in your day-to-day work. Before long, it will become second nature.

Similar Posts