Beginners' guide to Git

Introduction:

If you're someone associated with computer science or coding, you've probably heard terms like Git, GitHub, and Version Control System (VCS). Even if you're not sure what they are or what they do, these terms are familiar to most people in the field.

In this article, I'll dive deep into what a Version Control System (VCS) is, what Git and GitHub are, and the key differences between them.

prerequisites:

  • A GitHub account.

  • A command line interface.

  • A text editor (I will be using VS Code).

  • Git Bash (optional)

A Short Note on Version Control System

A Version Control System (VCS) is a tool used to track and manage changes to the source code of a project or software over time. It allows developers—whether working individually or in teams—to monitor modifications, collaborate effectively, and maintain a complete history of changes.

If developers make a mistake in the codebase, a VCS enables them to revert to a previous version, compare the current version with an earlier one, and identify the issues. Additionally, it allows them to run a stable, older version of the software while the faulty version is being fixed, ensuring that users experience minimal disruption.

In other words, a Version Control System is like a "time machine" for your codebase. It allows you to go back to previous versions to fix current issues while minimizing disruption for the entire team.

Git and Git Hub and their differences:

Git is a software and Git Hub is a service

Understand it with this analogy: You have gone to Switzerland for a tour.

Scenario-1: You went there, had an awesome time and came back. But in the mean time You did not take any camera or phone so you don’t have any photo or video. So after some time you might forget some details about the tour

This is like writing codes in your local machine. If something goes wrong It’s hard to get the code back into it’s original form. Sometimes impossible.

Scenario-2: This time you carried a camera and took pictures. So later you won’t forget your journey.

This is like Git. Writing code and use git to track your code. So later If something is messed up you can simply go back and use the perfect code which is saved in Git.

Scenario-3: You have pictures and videos of Your Journey. But no one can see that. So you want to share them with your friends. That’s why you posted your photos on Instagram.

It’s like Git Hub. You wrote a code saved and tracked with Git and then posted on Git Hub. So that others can see your code and collaborate.

Your code is saved right now Even if you lose your Computer you can retrieve your code with the help of Git Hub. Just like You can retrieve your photos from Instagram even after You lose Your phone.

NOTE-1: Just like Instagram is one of many social media platforms like Face-Book, Snapchat etc. Git Hub is one of the many platforms like GitLab or Bitbucket, that support Git repositories.

NOTE-2: Just like You can keep your photos and videos saved without posting them on any Social media , You can keep your code saved on git without uploading them on Git Hub

NOTE-3: Just like You can tag your friends on a post and also your friends can like comment share your post, You can collaborate with someone on Git Hub or someone can star your repo.

Install Git

To install Git, you can either use the command line or download the installer from the official website. Git is compatible with Windows, macOS, and Linux, and you can find the installation files on the official Git website: https://git-scm.com/downloads.

Account on GitHub

visit GitHub and create an Account there. Creating an account is very simple. Later in the blog I’ll show you how to link Git and GitHub.

Git basic commands:

Git uses a unique naming convention that differs from everyday terminology. For instance, what we usually call a "folder" is referred to as a repository or repo in Git. Similarly, instead of "alternate timeline," Git uses the term branch. Throughout this tutorial, we’ll stick to Git's naming conventions for consistency.

Check Git version:

Once you’re done installing Git. You can check the version of Git on your terminal

$ git --version

If you don’t already have git this will prompt open an installer. So If you haven’t installed it yet just install it. If you have git already, it’ll just show you which version of git you have installed.

Git work Flow:

This is a simple work flow usually developers maintain while using Git.

What is a Repository?

A repository (or repo for short) is like a folder or storage space for your project. It's where all the files, documents, and history of your project are kept. Think of it as a digital filing cabinet where everything about your project is stored, including previous versions of your files, so you can go back to them anytime if needed.

Types of Repositories:

There are two types of repositories

  1. Local Repository:

    This is the version of the repository that you keep on your own computer. You can work on your project, make changes, and save them, all on your own machine.

  2. Remote Repository:

    This is the version of the repository that’s stored online (for example, on GitHub or GitLab). It’s like an online backup of your project, and it allows others to see and contribute to your project too.

A repository is where your project files are stored, changes are tracked, and others can view and collaborate on your work.

Repository Workflow:

Gemini_Generated_Image_t5c6pjt5c6pjt5c6.jfif

Use Git:

Create Folder:

Create a folder and open with VS Code (or your favorite code editor). Open Git Bash or terminal(Separately or VS Code integrated).

Now create 2 files named touch1.txt, touch2.txt. We will be learning Git by modifying these files

Create a Repo & Initialize Git:

Creating a repository is like creating a new folder on your system and turning it into a Git repository. It's essentially a regular folder where you’ll work on your project, but with Git tracking all the changes you make. To create a repository, you can use the following command:

Git init

Running this command in your project folder initializes it as a Git repository. In simple words Git has been initialized and has started tracking your project folder.

The “U” in the file stands for “Untracked”. It means although your folder is being tracked but the files in the folder are still untracked.

This .git is a hidden folder. If it doesn’t appear, don’t panic, the system by default hides it. You won’t be able to see this folder by running ls command.

To see this folder on command line

for mac or Linux :

ls -la

for windows whether run the same command on Git Bash or:

ls -Force

The .git directory in a Git repository is the hidden folder that contains all the information Git needs to track and manage your project. It is essentially the heart of the repository, where Git stores metadata and version history.

Git add command (Staging):

Git add command takes a file and makes puts it in staging area. A staged file is a file which is being tracked by Git and ready to be committed.

There are two ways of using git add

  1. Staging one file at a time:
git add <file_name>

This way we will be able to add/stage one file at a time.

  1. Staging all files together:
git add .

In a real life scenario you’ll have multiple changes at a single time. Since staging one file at a time takes a lot of time, developers mostly use git add . But you’re free to choose whatever you like.

Git commit

Now that your files are staged and being tracked by Git. It’s time to commit them. When you commit, you're recording a snapshot of your changes in the version history. Each commit acts as a checkpoint in the development process, allowing you to keep track of what was changed and why at that specific point in time.

git commit -m "Your commit message"

Here’s the explanation of this command:

  • git: You're using Git.

  • commit: You want to commit your changes.

  • m: This allows you to add message directly in the command.

  • "Added a new feature to the contact form": This is the commit message, explaining that the commit adds a new feature to the contact form.

But incase you forget to write the entire command then there will be an issue. For example:

git commit

This means you have committed but haven’t added a comment.

You’ll have 2 options here:

  1. Vim: If you forget to add message VS Code will git you Vim editor. Where you’ll have to follow the rules of Vim.

  2. If you don’t want to use Vim then run this command (It is mentioned in the configuration section):

git config --global core.editor "code --wait"

If you add this command before and then make the mistake of not adding the comment, then you’ll a a file opened on VS Code:

Here on top of the file Add you commit message and cut the file. And your message is added to the commit. Yes it is very easy. Since this is an easy way people mostly prefer to use this command instead of using Vim.

Git Status

The git status command in Git provides a detailed view of the current state of your working directory and staging area. It helps you understand:

  1. Changes Made: Which files have been modified but not yet staged for commit.

  2. Staged Files: Which files are ready to be included in the next commit.

  3. Untracked Files: Files that are not yet being tracked by Git.

git status

In this photo, there is one file that is tracked staged and another that is untracked and not staged. The file name written in green is staged and ready to be committed, while the file name written in red is not staged yet.

View Commit History

Commit History with details:

After working on a project for a while, you might want to see a history or list of all your commits in one place. Git makes this easy with the following command:

Git log

Now, let’s break down what the git log output shows:

  1. Commit ID:

    • The long yellow text is the unique commit ID associated with each commit. This ID helps identify and refer to specific commits.
  2. Author Name and Email:

    • The second line displays the name and email of the person who made the commit. This information is pulled from the details configured in your Git account.
  3. Date and Time:

    • The commit log also shows the exact date and time when the commit was made, helping you keep track of when changes were applied.
  4. HEAD and Branch:

    • In Git, HEAD is a pointer to the current commit in the repository, indicating the branch you are working on and the latest commit in that branch. We’ll explore HEAD and branches in more detail later in this tutorial.

By using git log, you can easily review the history of your project and keep track of all the changes made over time.

Commit History in one line

If you’ve made numerous commits, your terminal might get cluttered with detailed commit information. To simplify viewing the commit history, Git offers a more concise way with the following command:

Git log --oneline

With this commit we get to see the history of the a commit with less detail.

NOTE: The first few characters of the commit id works as fine as the full commit id. So it can be used without any problem

Remove Git add (Remove from stage area)

What if you staged a modification by mistake? Wouldn’t it be really nice to be able to un-stage the modification? Well the good news is that Git lets you un-stage a modification.

The command for un-staging is:

git restore --staged <file_name>

In the image above as you can see, a file was staged and then removed from the stage area with the command.

Remove unwanted Commit:

Sometimes, you may accidentally make a commit and want to remove it from the commit history. Git offers two methods to handle this: a safe way and a hard reset.

The safe way

If you made a commit by mistake but want to undo it without permanently losing your changes, use:

Git reset <commit_id>

For example, here you have many commits. But You want to remove commit 3-5. Then you’ll write this command:

Git reset <commit-2-commitid>

Git reset b701ac5 for this particular example.

What Happens?

  • The commit you specify (<commit-id>) remains intact and safe, but all commits after it are removed from the commit history.

  • The changes from the removed commits are un-staged, allowing you to modify or delete them as needed.

Git —hard reset

For a more drastic approach, you can permanently delete commits using the --hard option:

git reset --hard <commit-id>

What Happens?

  • Not only are the commits removed, but any changes associated with them are permanently deleted.

  • This method leaves no trace of the removed commits in the repository.

WARNING: While git reset --hard is powerful and easy to use, it is irreversible. The deleted commits are permanently erased and cannot be recovered.

Recommendation: Use the safer git reset method whenever possible. This way, the changes remain un-staged, giving you an opportunity to review and recover them if needed.

Git Diff and stash:

Git diff:

1. View un-staged Changes:

  • Compares the working directory with the staging area to show changes that are not staged yet.

  • Command:

git diff

2. View Staged Changes:

  • Once the changes are staged but not yet committed, you can compare the changes in the staging area.

  • Command:

git diff --staged

3. Compare Two Commits:

  • Shows the changes between two specific commits.

  • Command:

git diff <old_commit_id> <new_commit_id>

4. Compare a Branch with Another Branch:

  • Shows the changes between two branches.

  • Command:

git diff <old_commit_id> <new_commit_id>

Why git diff?

  • Reviewing code or file changes before committing.

  • Comparing differences between versions for debugging.

  • Identifying conflicts between branches during merges.

Git Stash:

In Git, when you’re working with multiple branches, you might need to switch to another branch for some reason. However, Git won’t allow you to switch branches without committing your changes first. In some cases, if there are merge conflicts, Git won’t even let you commit the changes, meaning you won’t be able to switch branches until you resolve the conflict. But what if there’s an emergency? This is where Git stash becomes valuable.

Stash allows you to save your changes in a temporary location without committing them. You can make changes to a file, stash them, and return later to apply those changes when convenient. It’s a handy tool for managing work in progress when switching tasks.

git stash

Look how Git initially prevented the branch switch but allowed it seamlessly after the changes were stashed.

Naming the stash

You can also name the stash by using the following command:

Terminal window

git stash save "Work in progress"

View the stash list

You can view the list of stashes by using the following command:

Terminal window

git stash list

Git Stash pop:

When you're ready to bring back the stashed changes, you can use the git stash pop command. This command applies the most recent stashed changes to your working directory and automatically removes them from the stash list. It’s a convenient way to retrieve and continue working on temporarily saved changes without keeping them in the stash.

git stash pop

Delete the stash

If you realize that the changes you stashed temporarily are no longer needed, you can remove them permanently

git stash pop
git stash clear

Once executed, this action cannot be undone, and any stashed changes will be lost. Use this command cautiously, specially if there are stashed changes you might still need.

Git Branches, Merge and Rebase

Git branch is one of the most powerful and useful features of Git, especially for collaboration and contributions. It allows you to create a copy of your project codebase and work on new features, bug fixes, or experiments without affecting the main code. With branches, you can keep the main codebase safe, make isolated changes, test them, and then merge them back into the main (or master) branch when they are ready. This makes managing and organizing development much easier.

Here in the picture above we can see 2 branches other than main.

For example in a project someone will work on the header section, someone will work on side bar section and someone will work on the login section. So each of them can create their own branch and work there without effecting others.

HEAD in git

In the image above, all the circles labeled "main," "Little Feature," or "Big Feature" are the HEADs of their respective branches. In simple terms, HEAD is a pointer to the current branch you're working on. It always points to the latest commit in that branch. When you create a new branch, it is automatically set as the HEAD of that branch.

the default branch used to be master, but it is now called main. There is nothing special about main, it is just a convention.

some terminologies:

  1. master and main are basically same. These are just naming conventions. Nowadays the original branch is called main but initially it was called master. so feel free to use either one. But stick to one for consistency and to avoid errors

  2. Similarly switch and checkout do the same work. Although they might have some key differences but they’re negligible. In modern time switch is used mostly but previously checkout used more

  3. In Git, -c, -b, --oneline, and similar options are called flags or options.

List all branches

You can list all branches using the following command:

Terminal window

git branch

List all branches means that you are going to see all the branches in your repository.

Creating a branch in Git:

git branch
git branch bugFix
git switch bugFix
  • git branch - This command lists all the branches in the current repository.

  • git branch bugFix - This command creates a new branch called bugFix.

  • git switch bugFix - This command switches to the bugFix branch.

Initially, there was only one branch, master. Then, you created a branch called bugFix and switched to it. After running git branch again, you can see that there are now two branches: master and bugFix.

Create and switch to new branch

git switch master
git switch -c new-branch

Here you went back to master branch, but this time instead of using 2 commands to create a new branch and switch to that branch, use one command to create and switch to that branch.

  • git switch: This is used to switch between branches in your Git repository.

  • -c : This flag stands for "create." It tells Git to create a new branch.

  • new-branch: This is the name of the new branch you're creating.

With this shortcut command if there’s no branch named “new-branch”, it’ll create one and switch to it but if there’s already a branch named “new-branch”, it’ll just switch without any error.

Use checkout to change branch:

git checkout master

This does the exact same work as switch.

git checkout -b master

It’s a short cut to create and switch to a new branch.

Rename a branch

You can rename a branch using the following command:

Terminal window

git branch -m <old-branch-name> <new-branch-name>

Delete a branch

You can delete a branch using the following command:

Terminal window

git branch -d <branch-name>

Merging branches

Fast Forward merge

There are many ways to merge two branches. But this is the simplest form. This is a fast-forward merge where you create a new branch from main and change that new branch but don’t not modify the main branch. So when you merge two branches there should not be any merge conflicts. So merging becomes very easy.

git checkout main
git merge bug-fix

git checkout main This command switches to the main branch.

git merge feature This command merges the bug-fix to the main branch.

Fast Forward can be useful when you want to merge a branch that has already been pushed to the remote repository.

Three Way Merge (Not Fast Forward Merge)

A Three-Way Merge in Git is a method of merging two branches that have diverged from a common base. This process uses three key points of reference to generate a new commit that represents the merged state.

In simpler terms, imagine you have a main branch and you create a bug-fix branch. After that, you make changes to both branches. Now, when you try to merge the two branches, there’s a chance of a merge conflict.

But the fun fact is that the process of merging in a Three-Way Merge is almost identical to that of a Fast-Forward Merge:

git checkout main
git merge bug-fix

But what happens if there are merge conflicts? You handle them as they arise—there’s no shortcut for resolving conflicts. You’ll need to manually decide what to keep and what to discard.

The good news is that tools like VS Code’s built-in merge editor make it much easier to resolve conflicts. These tools show you the conflicting lines and provide options to choose or combine changes effectively.

Merge Conflict Resolving

There are different types of merge conflicts, but let’s understand the concept with a simple example:

Imagine you have a main branch with a file named "file-1.txt" containing some content. Then, you create a new branch called thor. Since the thor branch is created from main, it will have all the content from the main branch up to the point of branching.

After that, you make changes to the same line in "file-1.txt" from both branches—main and thor. Now, when you try to merge the two branches, Git faces a dilemma: which version of the line should it accept? Since the same line has different content in both branches, Git cannot automatically decide, and this results in a merge conflict.

In such cases, you can either manually resolve the conflict by choosing which version to keep or by combining them or use other methods offered by VS Code.

git checkout main
git merge thor

Here as you can see in the image, I have changed one line from two different branches. That’s why git is giving me merge conflict.

Here are 4 ways I can fix:

  1. Manually: In this method I’ll have to decide which change I want to keep and remove other changes manually. This is very helpful and sometimes the best way but not the most time and energy saving method

  2. Accept Current Change: Click Accept Current Change option and keep the change made by main branch.

  3. Accept Incoming Change: Click Accept Incoming Change: option and keep the change made by *thor* branch (or the other branch).

  4. Accept both Changes: This option simply lets me keep both the changes.

Resolving Merge Conflict is a complicated matter. It can not be taught by any tutorial. Nothing but constant practice, study and understanding of the code base can fix merge conflict.

Git Rebase

Just like Git merge, Git rebase is a command in Git used to reapply commits from one branch onto another.

Here’s the command:

git rebase <branch_name>

But Git command is a bit different than Git merge.

Git merge Preserves the history of both branches, creating a merge commit. The history looks like a tree with branches and merges.

While Git rebase Rewrites history to create a linear sequence of commits and removes the branching structure by applying commits from one branch on top of another.

Visualize Git rebase and merge with this diagram:

Conclusion:

In this tutorial We learnt about Git and how to use Git in your project. After this tutorial you should have the basic understanding of Git. Now your task is to follow the tutorial and get some hands on experience by doing the work.