Mastering Git Basics: A Step-by-Step Guide for Developers

Introduction

Git is key to modern development, enabling version control and collaboration. This guide covers essential commands and workflows for beginners and pros alike.

Written At

2025-01-25

Updated At

2025-01-25

Reading time

3.5 minutes

Step 1: Set Up Git

Why it matters:Setting up Git correctly ensures you can seamlessly track and manage your code changes.

Key actions to take:

  1. Install Git: Download Git from https://git-scm.com/
  2. Configure User Identity: Use the following commands to set your username and email:
    bash
    git config --global user.name "Your Name"
    git config --global user.email "youremail@example.com"
    

Example:

If your name is Jane Doe, your commands will look like this:

bash
git config --global user.name "Jane Doe"
git config --global user.email "jane.doe@example.com"

Step 2: Initialize a Repository

Why it matters:A Git repository is where your project's version history is stored.

Key actions to take:

  1. Navigate to your project folder:
    bash
    cd /path/to/your/project
    
  2. Initialize Git in the folder:
    bash
    git init
    

Example:

If you're creating a repository for a new portfolio website, run:

bash
cd  ~/portfolio-website
git init

Step 3: Track Changes in Your Code

Why it matters:Git allows you to stage and commit changes, preserving snapshots of your project's history.

Key actions to take:

  1. Add files to the staging area:
    bash
    git add .
  2. Commit your changes:
    bash
    git commit -m "Initial commit"

Example:

When adding a new feature, your commit message might look like this:

bash
git commit -m "Added responsive navigation bar"

Step 4: Collaborate with GitHub or GitLab

Why it matters:Hosting platforms like GitHub or GitLab allow you to share your code and collaborate with teammates.

Key actions to take:

  1. Link your local repository to a remote repository
    bash
    git remote add origin https://github.com/username/repository.git
  2. Push changes to the remote repository
    bash
    git push -u origin main

Example:

If your project is called 'Task Manager', create the repository on GitHub, copy the URL, and run:

bash
git remote add origin https://github.com/janedoe/task-manager.git
git push -u origin main

Step 5: Handle Conflicts

Why it matters: Conflicts occur when multiple developers make changes to the same part of a file. Resolving them is a key skill.

Key actions to take:

  1. Identify the conflict using git status
  2. Open the file with conflicts and resolve them manually.
  3. Mark the conflict as resolved:
    bash
    git add <file>
  4. Commit the changes:
    bash
    git commit -m "Resolved merge conflict in <file>"

Example:

If a conflict occurs in index.html, your commit message might be:

bash
git commit -m "Resolved merge conflict in index.html"