Introduction to Git Installation, Usage, and Branches

By Anurag Singh

Updated on Jan 03, 2025

Introduction to Git Installation, Usage, and Branches

This tutorial is introduction to Git installation, usage, and branches.

Git is a powerful version control system that enables developers to track changes in code, collaborate efficiently, and manage software development projects. It is distributed, meaning every user has a complete history of the repository, ensuring redundancy and reliability. Understanding Git is essential for modern development workflows, from individual projects to large-scale team collaborations. How to install Git, use its essential commands, and work with branches to manage multiple versions of a project effectively. By the end, you will be equipped to integrate Git into your development process confidently.

Introduction to Git Installation, Usage, and Branches

Installing Git

To use Git, you first need to install it on your system.  On Linux, run:

For Ubuntu:

sudo apt update && sudo apt install git

For CentOS-based systems:

sudo yum install git  

For Windows:

download the installer from the official Git website and follow the setup instructions.

On macOS, Git can be installed via Homebrew using the command:

brew install git

After installation, confirm it by running following command: 

git --version 

Configuring Git

After installation, configure Git with your name and email using the commands:

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

This information is crucial because Git uses it to identify changes made by you. Use

git config --list

To verify the settings and ensure they are correct. Configuring Git ensures your commits are properly attributed to you.

Initializing a Git Repository

To start version control for a project, initialize a Git repository in your project directory using

git init 

This creates a hidden .git folder, which stores metadata and version history for the repository.

If you’re working with an existing project, use following command to download and initialize a repository:

git clone [repository_url]  

Git tracks only the files added to the repository; use following command to stage all files:

git add . 

Finally, commit the staged changes using:

git commit -m "Initial commit".

Tracking Changes

Git uses a three-stage workflow: working directory, staging area, and commit history. Changes in files can be staged using

git add filename

Review the staged changes with

git status or git diff --staged

Once satisfied, save these changes to the repository with following command:

git commit

Each commit represents a snapshot of your project, allowing you to revert or review its history at any time.

Viewing Commit History

To view the commit history, use the command

git log

This shows a list of commits, including their hash, author, date, and message.

To make it more readable, try following command for a concise view.

git log --oneline

Use following command to inspect a specific commit in detail:

git show [commit_hash]

Understanding the history helps track the evolution of your project and resolve any issues related to past changes.

Creating and Using Branches

Branches in Git are pointers to snapshots of your project’s history. They allow you to work on different features, bug fixes, or experiments in isolation without impacting the main codebase. This flexibility ensures your project remains stable while you can explore new ideas or fixes independently.

Creating a Branch

To create a new branch, use the command:

git branch branch_name

For example, git branch feature-login creates a branch named feature-login. This branch is a duplicate of the current branch at the point of creation, meaning it includes all existing commits up to that point.

Switching to a Branch

After creating a branch, switch to it using:

git checkout branch_name

Alternatively, with Git 2.23 and later, you can use:

git switch branch_name

For example, git switch feature-login moves you to the feature-login branch, where all new commits will be made.

Viewing Branches

To list all branches in your repository, use:

git branch

The output highlights the current branch with an asterisk (*). Use git branch -a to see both local and remote branches. Regularly reviewing branches helps you manage your work effectively.

Merging Branches

Once you complete work on a branch, you can merge it back into the main branch using:

git checkout main
git merge branch_name

For example, switching to main and running git merge feature-login will incorporate changes from feature-login into main. Always resolve any merge conflicts before committing the merge.

Deleting a Branch

After merging, delete the branch to keep your repository clean using:

git branch -d branch_name

For example, git branch -d feature-login deletes the feature-login branch locally. Use git push origin --delete branch_name to delete a remote branch.

Working with Remote Branches

Remote branches are versions of branches stored on a remote repository. To create a branch on a remote repository, push it using:

git push origin branch_name

To switch to a remote bran-ch locally, fetch it and create a local branch that tracks it:

git fetch origin
git checkout -b branch_name origin/branch_name

This workflow ensures collaboration with team members while maintaining branch isolation.

Best Practices for Branching

  • Use Descriptive Names: Name branches clearly, such as feature-user-authentication or bugfix-crash-on-login.
  • Keep Branches Short-Lived: Regularly merge completed branches to avoid diverging histories.
  • Rebase if Necessary: Before merging, use git rebase to clean up commit history, but only on local branches.
  • Protect Main Branches: Use access controls and continuous integration tools to protect critical branches like main or master.

Example Workflow

Start from the main branch:

git checkout main

Create and switch to a new branch:

git branch feature-profile-page
git switch feature-profile-page

Make changes, stage them, and commit:

git add .
git commit -m "Added profile page layout"

Merge the branch after completing work:

git checkout main
git merge feature-profile-page

Delete the branch locally and remotely:

git branch -d feature-profile-page
git push origin --delete feature-profile-page

Branches in Git offer a structured and efficient way to manage your codebase, enabling seamless collaboration and version control in any development project.

Merging and Resolving Conflicts

Merging in Git is the process of combining changes from one branch into another. It is commonly used to integrate feature branches into the main branch or synchronize changes across multiple branches. However, conflicts can arise when the same lines in a file are modified differently in the branches being merged. Understanding how to merge and resolve conflicts is critical for maintaining a clean and stable project history.

Types of Merges

Fast-Forward Merge:

If the branch being merged has changes that follow directly from the current branch, Git moves the branch pointer forward. No new commit is created in this case.

Example:

git merge branch_name

Three-Way Merge:

When branches have diverged, Git performs a three-way merge using the latest common ancestor, the current branch, and the branch being merged. This results in a new commit that represents the merge.

Performing a Merge

Switch to the branch you want to merge changes into:

git checkout main

Merge the other branch:

git merge feature-branch

Git will attempt to automatically merge the changes. If successful, the process ends with a new merge commit.

Understanding Merge Conflicts

Conflicts occur when Git cannot automatically reconcile differences between two branches. For example:

  • Both branches modify the same lines in a file.
  • One branch deletes a file that the other modifies.

When conflicts occur, Git halts the merge and marks the affected files as conflicted. Use git status to see a list of these files.

Resolving Merge Conflicts

Identify the Conflicted Files:

Run git status to list files with conflicts. These files contain conflict markers indicating the differing changes. For example:

<<<<<<< HEAD
Code from the current branch
=======
Code from the branch being merged
>>>>>>> feature-branch

Edit and Resolve:

Open the files and decide how to handle the differences. You can:

  • Keep one version.
  • Combine both changes.
  • Rewrite the section entirely.

Mark as Resolved. After resolving, stage the changes using:

git add filename

Complete the Merge. Commit the resolved changes:

git commit

Aborting a Merge

If the merge is too complex or unnecessary, abort it with:

git merge --abort

This restores the branch to its pre-merge state.

Tips for Avoiding and Handling Conflicts

Pull Changes Regularly:

Keep your branch updated by frequently pulling changes from the main branch.

git pull origin main

Make Small Commits:

Smaller, focused commits reduce the likelihood of conflicts and make them easier to resolve.

Use a GUI Tool:

Tools like GitKraken, SourceTree, or Visual Studio Code's Git integration provide visual interfaces for resolving conflicts.

Test After Resolving:

Always test your code after resolving conflicts to ensure functionality remains intact.

Example of Resolving a Conflict

Merge feature-login into main:

git checkout main
git merge feature-login

Git reports a conflict:

  • CONFLICT (content): Merge conflict in app.py
  • Automatic merge failed; fix conflicts and then commit the result.

Open app.py and resolve the conflict:

<<<<<<< HEAD
print("Welcome to the main branch")
=======
print("Welcome to the login feature")
>>>>>>> feature-login

Resolve by choosing one or combining both:

print("Welcome to the login feature in the main branch")

Mark the file as resolved:

git add app.py

Complete the merge:

git commit -m "Merged feature-login into main with conflict resolution"

Merging and resolving conflicts are essential skills for managing collaborative projects. By following best practices and leveraging Git's powerful tools, you can minimize conflicts and handle them efficiently when they arise.

Remote Repositories

A remote repository in Git is a version of your repository hosted on a server or cloud service, such as GitHub, GitLab, or Bitbucket. Remote repositories enable collaboration by allowing multiple developers to push, pull, and synchronize changes to a central location. They are essential for distributed version control workflows.

Adding a Remote Repository

You can connect your local repository to a remote repository using the git remote add command. For example:

git remote add origin https://github.com/username/repository.git
  • origin: This is the default alias for the remote repository, but you can choose any name.
  • The URL specifies the location of the remote repository.

Run git remote -v to verify the connection and see the URLs for fetch and push.

Cloning a Remote Repository

To create a local copy of a remote repository, use the git clone command:

git clone https://github.com/username/repository.git

This command downloads the repository and sets the remote origin automatically. The resulting directory contains the full project history and files.

Fetching Changes from a Remote Repository

Fetching downloads updates from the remote repository without altering your local branch:

git fetch origin

This command updates your local metadata and branches but does not merge the changes. It's a safe way to review updates before applying them.

Pulling Changes from a Remote Repository

Pulling fetches updates and merges them into your current branch:

git pull origin main

This is equivalent to running git fetch followed by git merge. Use it when you are ready to integrate changes from the remote repository.

Pushing Changes to a Remote Repository

To share your local changes with the remote repository, use the git push command:

git push origin branch_name

For example, git push origin main uploads the changes in your local main branch to the main branch of the remote repository. If you’re creating a new branch, push it with:

git push -u origin new_branch

The -u flag sets the upstream tracking branch, allowing you to use git push without specifying the remote or branch name in the future.

Viewing Remote Repositories

List all configured remotes in your repository:

git remote -v

This displays the aliases and URLs of your remotes, such as origin and additional remotes if configured.

Renaming or Removing a Remote

Rename a remote using:

git remote rename old_name new_name

Remove a remote using:

git remote remove remote_name

These commands help maintain your configuration as repositories evolve.

Tracking Remote Branches

When you clone or fetch a repository, Git tracks remote branches. Use git branch -r to view these branches:

git branch -r

To track a remote branch locally, create a branch linked to the remote branch:

git checkout -b local_branch origin/remote_branch

Synchronizing with Remote Changes

  • Fetch Before Pull: Fetching allows you to review changes before merging them into your local branch.
  • Resolve Conflicts Locally: If a push fails due to remote updates, pull the changes, resolve conflicts, and push again.
  • Avoid Force Push: Use git push --force only when absolutely necessary, as it overwrites changes on the remote branch.

Working with Multiple Remotes

You can work with multiple remotes in the same repository. For example:

Add a second remote:

git remote add upstream https://github.com/another/repository.git

Fetch changes from it:

git fetch upstream
  • Merge or cherry-pick changes as needed.
  • Example Workflow with Remote Repositories

Clone the repository:

git clone https://github.com/username/project.git

Make changes and commit them locally:

git add .
git commit -m "Implemented feature X"

Pull updates from the remote:

git pull origin main

Push your changes to the remote repository:

git push origin main

Best Practices for Remote Repositories

  • Use Descriptive Commit Messages: Helps collaborators understand changes.
  • Keep Your Fork Up-to-Date: Regularly fetch and merge upstream changes if you’re working on a fork.
  • Use Protected Branches: Enable branch protection to enforce reviews and prevent accidental overwrites.
  • Collaborate with Pull Requests: Use pull requests to review and merge changes.
  • Secure Your Repositories: Use SSH keys or personal access tokens for authentication.

Remote repositories are the backbone of collaborative development, enabling teams to work efficiently and effectively on shared codebases. By mastering remote repository workflows, you can seamlessly contribute to projects of any scale.

Best Practices for Using Git

  • Write meaningful commit messages to describe changes clearly.
  • Commit frequently to ensure a detailed and recoverable history.
  • Use branches for new features, bug fixes, or experiments to keep the main branch stable.
  • Regularly pull changes from the remote repository to stay updated.
  • Review changes using git diff before committing to avoid accidental errors.

Git is an indispensable tool for software development, offering a robust way to manage changes and collaborate effectively. Mastering Git's essential commands and practices ensures better productivity and project management in any development environment.

Checkout our dedicated servers India, Instant KVM VPS, and Web Hosting India