Conquer Version Control: Git & GitHub - Your Beginner’s Guide

zuxcode

Alfred Nwanokwai

Posted on May 1, 2024

Conquer Version Control: Git & GitHub - Your Beginner’s Guide


Git and GitHub

Ever lost precious code after accidentally overwriting it? Dread no more! Master version control with Git and GitHub, the powerful tools that let you:

  • Effortlessly rewind your code to any previous state.
  • Collaborate seamlessly with others on projects.
  • Track every change made to your codebase.

This beginner-friendly guide will equip you with the essential skills to conquer Git and GitHub. We’ll break down key concepts into easy-to-follow steps, navigate the GitHub interface, and show you how to collaborate effectively. Get ready to unlock a stress-free coding experience and say goodbye to version control confusion!

How to Set Up Git for Your Machine

Before diving into the world of Git and GitHub, you'll need Git installed on your local machine. The installation process varies slightly depending on your operating system. Here's a breakdown for the most common ones:

Install Git on Windows Machine:

  1. Download the Git Installer: Head over to the official Git website and download the latest version of the installer for your system (32-bit or 64-bit).
  2. Run the Installer: Double-click the downloaded installer and follow the on-screen instructions. It’s recommended to keep the default options selected during installation. One important choice is selecting "Use Git from the Windows Command Prompt" if you want to use Git directly from the command prompt. Otherwise, Git Bash, a Unix-like shell environment, will be your primary tool for interacting with Git.
  3. Verify Installation: Open a command prompt (or Git Bash) and type
git --version

Enter fullscreen mode Exit fullscreen mode

If Git is installed correctly, you should see the installed version number displayed.

Install Git on macOS Machine:

  1. Using Homebrew (Recommended): If you’re comfortable with the command line and use a package manager like Homebrew, installing Git is a breeze. Open your terminal and run the following command:
brew install git

Enter fullscreen mode Exit fullscreen mode
  1. Using the Installer: Alternatively, you can download the official Git installer for macOS from the Git website. The installation process is straightforward - just follow the on-screen instructions.
  2. Verify Installation: Open your terminal and type
git --version

Enter fullscreen mode Exit fullscreen mode

If Git is installed successfully, you’ll see the installed version number displayed.

Install Git on Linux Machine:

Most Linux distributions come with Git pre-installed. To check if it’s already available, open a terminal and type

git --version

Enter fullscreen mode Exit fullscreen mode

If Git is not found, you can install it using your distribution’s package manager. The specific command will vary depending on your distro, but it’s typically something like

sudo apt-get install git

Enter fullscreen mode Exit fullscreen mode

for Debian-based systems

or

sudo yum install git

Enter fullscreen mode Exit fullscreen mode

for RPM-based systems.

Congratulations! You’ve successfully installed Git on your machine. Now you’re ready to explore the exciting world of version control and unlock the power of Git and GitHub!

Git for Beginners: Configuring Your Local User Information

Now that you have Git installed, let’s personalize it! Git uses your name and email address to identify you when you commit changes to your code. Here’s how to configure your local user information:

  • Open your terminal or command prompt. This is where you’ll interact with Git using text commands.
  • Run the following command:
git config --global user.name "Your Name"

Enter fullscreen mode Exit fullscreen mode

Replace "Your Name" with your actual name. This sets the name associated with your Git commits.

  • Configure your email address:
git config --global user.email "your_email@example.com"

Enter fullscreen mode Exit fullscreen mode

Run this command, replacing "your_email@example.com" with your valid email address:

  • Verify your configuration (optional):

Use the following command to see your current Git settings:

git config --list

Enter fullscreen mode Exit fullscreen mode

This should display your username and email address under the user.name and user.email keys, respectively.

Why is this important?

  • Proper Attribution: When you commit changes to a project (local or remote), your username and email will be associated with those changes. This helps maintain a clear history of who made what modifications.
  • Consistent Identity: Using the same email address across different Git repositories ensures a consistent identity within the Git ecosystem.

Set Your Default Branch Name (Optional):

Run the following command to set "master" as your preferred default branch name for newly created repositories:

git config --global init.defaultBranch master

Enter fullscreen mode Exit fullscreen mode

Note: This step is optional. The default branch name is typically master, but some projects might use main or a custom name. Choose the name that aligns with your project’s conventions.

Why Set a Default Branch?

Setting your preferred default branch name streamlines the process of creating new Git repositories. By default, Git uses master, but you can customize it to suit your workflow.

Congratulations! You've successfully configured your local Git user information and (optionally) set your default branch name. Now you're ready to start using Git commands and interact with version control systems effectively!

Git Fundamentals

  1. Open your terminal or command prompt and navigate to the directory containing your project files.
  2. Type the following command and press Enter:

Initializing Your Project:

The first step to using Git with your project is to initialize a Git repository. This creates the essential structure for Git to track changes. Here’s how to do it:

git init

Enter fullscreen mode Exit fullscreen mode

If successful, Git will create a hidden folder called .git in your project directory. This folder stores all the Git-related information, including the history of your project’s changes.

Git status

The git status command provides a snapshot of your project’s current state, revealing valuable information about changes and the overall Git workflow. Here’s how to use it:

git status

Enter fullscreen mode Exit fullscreen mode

Adding Changes to the Staging Area

Think of your working directory as your active workspace where you edit and modify project files. Git keeps track of changes through "commits," but before a commit happens, there’s a crucial step: staging. The git add command allows you to add specific changes from your working directory to a temporary holding zone called the staging area. These changes are then designated for inclusion in your next commit.

Git add

There are two main ways to use git add:

git add <filename>

Enter fullscreen mode Exit fullscreen mode

Replace <filename> with the actual name of the file you want to stage. This adds only that specific file to the staging area.

git add --all

Enter fullscreen mode Exit fullscreen mode

Or

git add -A

Enter fullscreen mode Exit fullscreen mode

Or

git add .

Enter fullscreen mode Exit fullscreen mode

The dot (.) acts as a wildcard, signifying that you want to add all modified files in the current directory (excluding untracked files) to the staging area. This can be useful if you’ve made multiple changes and want to include them all in the next commit.

Removing a File from the Staging Area (Without Deleting the File):

Let’s say you’ve added a file to the staging area using git add but decide you don’t want to include it in the next commit. You can remove it from the staging area without deleting the actual file from your working directory.

git rm --cached <filename>

Enter fullscreen mode Exit fullscreen mode

The --cached flag tells Git to remove the file from the staging area only, leaving the physical file intact in your working directory.

git restore

The git restore command in Git serves a dual purpose: restoring files and restoring the contents of the staging area.

git restore <filename>

Enter fullscreen mode Exit fullscreen mode

Replace <filename> with the actual name of the file you want to restore.

Discarding vs. Restoring:

By default, git restore discards any local modifications in the file. Use the

git restore -k <filename>

Enter fullscreen mode Exit fullscreen mode

to keep those modifications while restoring the file content from another source.

Scenarios for Using git

  • Imagine accidentally modifying a file or even deleting it. git restore can help you recover the file from a previous state.
  • It allows you to restore a file to its condition at the last committed version (HEAD), the index (staging area), or a specific commit in your history.

Restoring the Staging Area:

The git restore --staged command allows you to remove a file from the staging area without affecting the actual content of the file in your working directory. This is particularly useful when you’ve accidentally added changes or want to revise them before committing.

git restore --staged <filename>

Enter fullscreen mode Exit fullscreen mode

Replace <filename> with the actual name of the file you want to unstage.

Git Rename or move a File

The git mv command in Git serves two purposes: renaming and moving files within your project’s repository. It’s a convenient way to manage changes to your file structure while keeping track of those changes in your version control history.

git mv <old filename> <new filename>

Enter fullscreen mode Exit fullscreen mode

Replace <old filename> with the actual name of the file you want to rename or move and replace <new filename> with the new name of the file you want.

Git Remove a File from Git’s Tracking (Staged or Unstaged):

This command removes a file from both Git’s tracking and your working directory. It essentially erased the file from your project’s version control history and deletes it from your local filesystem.

git rm <filename>

Enter fullscreen mode Exit fullscreen mode

Replace <filename> with the actual name of the file you want to delete and untrack.

Git .gitignore File

The .gitignore file is a plain text file located in the root directory of your Git repository. It acts as a set of instructions for Git, specifying files and patterns that should be excluded from version control. This prevents unnecessary files from being tracked by Git and cluttering your commit history.

  1. Create a new text file named .gitignore (note the leading dot) in the root directory of your Git repository.
  2. Open the .gitignore file in a text editor and add lines specifying the files or patterns you want to exclude.

Git Commit.

Git commit acts like a save point in the history of your project. It captures a permanent record of the changes you’ve made to your files at a specific point in time. Imagine it like taking a picture of your project at a particular stage of development.

git commit -m "message"

Enter fullscreen mode Exit fullscreen mode

Git Environment

There are three environments in git

Working Files

working files refer to the files in your project directory that have been modified but haven’t yet been added to the staging area for the next commit. Imagine your project directory as your messy desk. The working files are the papers, notes, and unfinished projects scattered around – they haven’t been organized or filed away yet.

Staging Area

The staging area in Git acts like a holding zone for changes you plan to include in your next commit. Imagine you’re cleaning your room and have a pile of clothes on your bed. These are the modified files in your project that haven’t yet been "committed" or saved permanently

Commit

commit represents a permanent snapshot of your project’s state at a specific point in time. It captures the changes you’ve made to the files that were staged using the git add command

Git Skip Staging

The command git commit -a -m "<commit message>" combines three functionalities in Git for creating a commit:

Staging all modified and deleted files (-a flag):

  • The -a flag with git commit instructs Git to automatically add all modified and deleted files in your working directory to the staging area.
  • This bypasses the need for you to use git add on individual files or patterns.

Creating a commit (git commit):

  • The core function of git commit is to capture a snapshot of the currently staged files and store it as a permanent record in your Git repository.
  • This snapshot represents the state of your project at that specific point in time.

Adding a commit message (-m "<commit message>"):

  • The -m flag with git commit allows you to provide a descriptive message that explains the changes included in the commit.
  • This message is crucial for understanding the project’s history and what modifications were made in that particular commit.
  • Replace <commit message> with a clear and concise explanation of the changes you’ve made.

Git Amend commit

Amending a commit in Git allows you to modify an existing commit, but not directly. It’s like realizing you forgot to add something important to a photograph you just took, and wanting to fix it without having to retake the entire picture.

git commit -m "<message>" --amend

Enter fullscreen mode Exit fullscreen mode

Git log

The git log command acts like a time machine for your project in Git. It allows you to explore the history of your project, revealing all the changes made to your codebase over time. It’s like flipping through a logbook that documents each significant event (commit) in your project’s journey.

git log

Enter fullscreen mode Exit fullscreen mode

What git log shows you:

  • Commit Hashes: Each commit is identified by a unique code (hash), allowing you to pinpoint specific versions of your project.
  • Author Information: You see who made the commit (author name and email).
  • Commit Date and Time: It displays the exact timestamp of when the commit was created. Commit Message: This is the message you provided when creating the commit, ideally summarizing the changes made.

Enhancing git log with options:

  • Limiting the output: You can specify a number e.g.
git log -2

Enter fullscreen mode Exit fullscreen mode

to see only the last two commits.

  • Filtering by author: Use
git log --author="<name>"

Enter fullscreen mode Exit fullscreen mode

to view commits made by a specific author.

  • Searching for keywords: Include a keyword after git log to search for commits containing that term in the message e.g.
git log fix

Enter fullscreen mode Exit fullscreen mode

shows commits mentioning "fix"

  • Abbreviated version: the
git log --oneline

Enter fullscreen mode Exit fullscreen mode

command provides a concise way to view your Git commit history.

  • Viewing full commit diff: Use
git log -p

Enter fullscreen mode Exit fullscreen mode

to see the detailed changes introduced in each commit.

Git diff

The git diff command is a workhorse in Git, allowing you to compare the differences between various data sources within your project's version control system. Here's a breakdown of its functionalities:

git diff

Enter fullscreen mode Exit fullscreen mode

What git diff can compare:

  • Working Directory vs. Staging Area: You can see the changes you’ve made in your working directory that haven’t yet been staged for the next commit.
  • Staging Area vs. Repository: It can show the difference between the files currently staged and their most recent committed version in your Git repository.
  • Two Commits: You can compare the changes introduced between any two specific commits in your project history.
  • Working Directory vs. Specific Commit: It allows you to see how your working directory’s files differ from a particular commit in the past.

Common Options with git diff:

git diff --cached

Enter fullscreen mode Exit fullscreen mode

shows the difference between the staging area and the latest commit (useful for reviewing staged changes).

git diff <commit_one> <commit_two>

Enter fullscreen mode Exit fullscreen mode

This syntax allows you to compare the specific commits

Git reset

The git reset command in Git is a powerful tool for manipulating the state of your Git repository, but it’s important to understand its effects carefully before using it. It allows you to move the HEAD pointer (which points to the latest commit) to a different position in your commit history. However, unlike some other Git commands, git reset can have significant consequences, so it’s crucial to use it cautiously

git reset

Enter fullscreen mode Exit fullscreen mode

Modes of git reset:

There are three primary modes of git reset, each affecting different parts of your Git repository:

  • git reset (soft reset): This mode moves the HEAD pointer to a specific commit but doesn’t modify the working directory or staging area. Your working directory remains unchanged, but any changes you made since the commit you reset to are no longer tracked by Git.
git reset <commit>

Enter fullscreen mode Exit fullscreen mode
  • git reset --mixed (mixed reset - default): This mode moves the HEAD pointer and also discards any changes in the staging area (index). However, it keeps the changes in your working directory, leaving them untracked. This can be useful if you accidentally staged unwanted changes.
git reset --mixed <commit>

Enter fullscreen mode Exit fullscreen mode
  • git reset --hard (hard reset): This is the most drastic mode. It moves the HEAD pointer, discards changes from the staging area (like mixed reset), and also discards all uncommitted changes in your working directory. This essentially reverts your working directory to the state it was in at the specified commit.
git reset --hard <commit>

Enter fullscreen mode Exit fullscreen mode

Collaborative Workflows with Git and GitHub

Git branch

Git branch command is fundamental for managing different lines of development in your project. Here’s a breakdown of what it allows you to do:

  • Creating Branches: Imagine you’re working on a new feature or fixing a bug. You can use
git branch <branch_name>

Enter fullscreen mode Exit fullscreen mode

to create a new branch isolated from the main development line (often called master). This creates a copy of the latest commit at that point, allowing you to work on your changes without affecting the main project code.

  • Listing Branches: Use
git branch

Enter fullscreen mode Exit fullscreen mode

on its own to display a list of all the existing branches in your local repository. It will indicate which branch is currently checked out (usually identified by an asterisk).

  • Switching Branches: Once you have multiple branches, you can switch between them using
git checkout <branch_name>

Enter fullscreen mode Exit fullscreen mode

Or

git switch <branch_name>

Enter fullscreen mode Exit fullscreen mode

This changes your working directory to reflect the content of the specified branch.

  • Deleting Branches: When a branch’s work is complete and merged into the main codebase, you can delete it using
git branch -d <branch_name>

Enter fullscreen mode Exit fullscreen mode

Or

git checkout -d <branch_name>

Enter fullscreen mode Exit fullscreen mode

However, it’s generally recommended to only delete branches that have already been merged and are no longer needed.

  • create branch and switch branch :Combine checkout with branch creation using
git checkout -b <branch_name>

Enter fullscreen mode Exit fullscreen mode

Or

git switch -c <branch_name>

Enter fullscreen mode Exit fullscreen mode

This creates a new branch and switches to it simultaneously.

  • Force switch branch: switches branches even if you have uncommitted changes in your working directory (use with caution as it can lead to data loss).
git checkout -f <branch_name>

Enter fullscreen mode Exit fullscreen mode
  • Detached HEAD State:

Running

git checkout <commit_hash> 

Enter fullscreen mode Exit fullscreen mode

allows you to checkout a specific commit. This detaches your HEAD pointer from any branch and points it directly to that commit. Your working directory reflects the state of the chosen commit, but you’re not technically on any particular branch.

  • Restoring Files:

If you’ve accidentally deleted a file or want to revert changes, git checkout can help. Use

git checkout <filename>

Enter fullscreen mode Exit fullscreen mode

to restore the file from the latest committed version in your current branch.

Merge branch

The git merge command in Git plays a vital role in combining changes from different branches into your project’s history. It allows you to seamlessly integrate work done on separate branches and maintain a clear, unified codebase.

git merge -m <"message"> <branch_name>

Enter fullscreen mode Exit fullscreen mode

Resolving Merge Conflicts:

  • Git will mark the conflicting sections in the affected files with special markers (usually <<<<<<< and >>>>>>>). You need to manually edit these files, choose the desired changes, and remove the conflict markers to create a resolved version.
  • Once you’ve resolved all conflicts and staged the changes, you can use git commit to create a new merge commit that captures the combined history of both branches.

Adding Remotes:

To connect your local repository to a remote one, use

git remote add <remote_name> <url>

Enter fullscreen mode Exit fullscreen mode
  • <remote_name> is a name you choose to identify the remote repository (e.g., "origin" is a common convention).
  • <url> is the web address of the remote repository.

Fetching and Pulling:

Once you have a remote configured, you can use

git fetch <remote_name>

Enter fullscreen mode Exit fullscreen mode

to retrieve information about the remote branches and commits without actually merging them into your local repository.

Then

git merge 

Enter fullscreen mode Exit fullscreen mode

To merge the changes.

Git pull

git pull is a streamlined way to fetch updates and merge them into your local branch, keeping your project synchronized with the remote repository

git pull

Enter fullscreen mode Exit fullscreen mode

Managing Remotes:

  • You can rename an existing remote using
git remote rename <old_name> <new_name>

Enter fullscreen mode Exit fullscreen mode
  • To remove a remote connection entirely, use
git remote remove <remote_name>

Enter fullscreen mode Exit fullscreen mode

Git push

  • Making the first push to a remote branch:

The git push -u command in Git is a shortcut specifically designed to streamline your workflow when pushing commits to a remote repository for the first time

git push -u <remote_name> <branch_name>

Enter fullscreen mode Exit fullscreen mode
  • Pushing Changes

The core function is to upload your local branch commits to a remote repository. This typically involves specifying the remote repository and the branch name you want to push to.

git push

Enter fullscreen mode Exit fullscreen mode

git rebase

The git rebase command in Git allows you to rewrite your commit history by rearranging, squashing, or editing commits. It’s a powerful tool, but it’s important to understand its implications before using it, especially in collaborative workflows.

Checkout to a different branch and run

git rebase master

Enter fullscreen mode Exit fullscreen mode

The command git rebase master specifically instructs Git to rebase your current local branch on top of the master branch. Here’s what it does and some key considerations:

Reordering Commits:

Imagine you have a series of commits on your local branch, and you decide the order doesn’t logically reflect the development process. git rebase allows you to replay your commits on top of a different base commit, effectively changing their order.

Squashing and Editing Commits:

You can use git rebase to combine multiple commits into a single commit (squashing). This can help clean up your commit history and make it easier to understand.

Additionally, you can edit individual commits by making changes to their message or code during the rebasing process.

Interactive Rebasing:

The most powerful form of rebasing is interactive rebasing, initiated with

git rebase -i <branch_name>

Enter fullscreen mode Exit fullscreen mode

This opens an interactive editor where you can see a list of your commits. You can then choose to:

  • pick: Keep the commit unchanged. (default)
  • squash: Combine the commit with the previous commit.
  • fixup: Similar to squash, but discards the commit message of the current commit.
  • edit: Modify the content and message of the commit.
  • drop: Discard the commit entirely.

The command

git rebase -i --root

Enter fullscreen mode Exit fullscreen mode

is an advanced Git operation that allows you to rewrite your entire Git repository’s history from the very beginning (the root commit). It involves interactive rebasing, giving you fine-grained control over how you rearrange, squash, or edit commits across your entire commit history.

Due to the potential for disrupting your entire history and causing issues for collaborators, it’s generally recommended to avoid using git rebase -i --root unless you fully understand its implications and have a specific need for such a drastic rewrite.

Congratulations! You’ve unlocked Git & GitHub! Now you can collab seamlessly, track changes with ease, and conquer version control. Want more? Subscribe to our newsletter for new articles and follow us on Twitter @zuxcode for discussions and updates. Happy coding!

💖 💪 🙅 🚩
zuxcode
Alfred Nwanokwai

Posted on May 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related