Robin.te.Hofstee

How Git Works

Robin te Hofstee3 min readViews1
How Git Works

Git is a distributed version control system that allows multiple people to collaborate on a project while maintaining a complete history of all change

How Git Works

Git is a distributed version control system that allows multiple people to collaborate on a project while maintaining a complete history of all changes. Unlike centralized systems, every Git user has a full copy of the repository, enabling offline work and improved collaboration.

How Does Git Work?

At its core, Git works through repositories (repositories) and commits. A commit represents a snapshot of your project at a specific point in time. When you make changes to files, you stage those changes and create a commit to record them in history.

Basic Git Workflow

  1. Initialize a Repository: Start by initializing a new Git repository in your project directory:

    git init
  2. Stage Changes: Track changes you want to commit by staging them:

    git add <file>
  3. Commit Changes: Commit the staged changes with a descriptive message:

    git commit -m "Initial commit"
  4. Push to Remote: If you're working with others, push your changes to a remote repository (like GitHub):

    git remote add origin <remote-url>
    git push -u origin main

Branching in Git

Branches allow parallel development by creating separate lines of development. The main branch is typically the primary branch, while other branches are created for features or bug fixes.

# Create and switch to a new branch
git checkout -b <branch-name>

Merging Changes

When you want to bring changes from one branch into another, you use the merge command:

# Switch to the branch you want to merge into
git checkout <target-branch>
 
# Merge the source branch into the target
git merge <source-branch>

Pull Requests and Code Reviews

When contributing to a project, you'll often create a fork of the repository, make changes, and submit a pull request to request that your changes be merged into the original repository. This allows for code reviews and discussion before changes are accepted.

Resolving Conflicts

When merging branches with conflicting changes, Git will alert you to the conflict. You'll need to manually resolve the conflict by editing the affected files, then stage and commit the resolved changes:

# After resolving conflicts
git add <resolved-file>
git commit -m "Resolve merge conflict"

Summary

Git is a powerful tool for tracking changes and collaborating on projects. Understanding concepts like commits, branches, merging, and pull requests is essential. This tutorial covered the basics of how Git works, including key concepts and workflows. With practice, you'll become proficient in using Git to manage your projects effectively.

Share this post
Robin te Hofstee

Written by Robin te Hofstee

Technology enthusiast with a deep love for programming. Sharing practical guides on React, Next.js, Linux and self-hosting.