Skip to main content

Command Palette

Search for a command to run...

Making Peace With Git

Git Fundamentals for Beginners

Updated
9 min read
Making Peace With Git

Have you ever been in a dilemma where you cant find the project you have been working on, or the ability to be able to share your code with your peers to collaborate or get it reviewed? If so, you need Git in your life.

We'll explore Git from the ground up, what it is, why it is the holy grail of the developers, and how you can start using it today. Whether you're a complete beginner or looking to solidify your understanding, this article will equip you with the essential knowledge to manage your code like a pro.

What is Git?

Git is a distributed version control system (VCS). It helps the developers to track changes in their codebase over a period of time, revert to previous version if something breaks, save snapshot of your work, add new features without affecting stable codebase, and collaborate with your fellow developers.

Key Characteristics of Git

  • Distributed: Every developer has a complete copy of the project history on their local machine.

  • Fast: Most operations are performed locally, making Git incredibly quick

  • Free and Open Source

  • Branching-Friendly: Creating and merging branches is lightweight and efficient

Think having the power of Dr. Strange and the Flash together, you can go back in time and revert changes or track the timeline of the code and have the ability to work on code in multiple branches like a parallel dimension. Sounds pretty amazing.

Why Git is Used?

Git has become the industry standard for version control. Here's why developers including you, rely on it:

1. Track Changes Over Time

Git records every modification to your codebase, providing the knowledge of who changed what, when, and why. This historical record is invaluable for understanding how your project evolved and debugging issues.

2. Collaboration

Multiple developers can work on the same project simultaneously without the stress and multiple Zoom or Google meets. Git intelligently merges the changes and helps resolve conflicts when they arise. (Although, every dev prays for no conflict)

3. Experiment Safely with Branches

Want to try a new feature without breaking your stable code? Create a branch! Branches allow you to develop features, fix bugs, or experiment in isolation. If things go well, merge them; if not, simply delete the branch.

4. Backup and Recovery

Since every developer has a full copy of the repository, losing work is much harder. Made a mistake? Git makes it easy to undo changes and recover previous versions.

5. Integration with Modern Tools

Git integrates seamlessly with platforms like GitHub, GitLab, and Bitbucket, providing code hosting, collaboration features, CI/CD pipelines, and more.

💡
To check if Git is installed on a local machine, type the command git --version in the terminal.

What is GitHub?

Github is a product that is a cloud based hosting service for Git repositories. GitHub is not Git, it just provides hosting but for your codebase. There are other hosting platforms like GitLab and Bitbucket.

Git Basics and Core Terminologies

Before we take a dive into Git commands, lets understand some important terminologies so that we don’t scratch our heads later.

  1. Repository or Repo

    It is a directory that contains your project files and all the track records of your changes. It includes a hidden .git folder that stores all version control information.

    • Local Repository: The project version on your local machine

    • Remote Repository: The project version hosted on a server like GitHub

  2. Working Directory
    The folder on your local machine where you actively edit your files. It contains the current state of your project that you can track and edit.

  3. Index or Staging Area
    It is a platform between your machine i.e. the working directory and the repository. They will hold the file before you commit them, allowing you to choose the the files and the changes you want to commit.

  4. Commit
    This is the snapshot of your project. The commit holds a unique ID called hash, author information, a commit message to describe the changes, timestamp, and reference to your previous commit. One commit at a time builds your project.

  5. Branch
    It is an independent path of development. Git branch is similar to a Tree branch, like a tree trunk the default branch is called main. You create new brach to work on a new feature or bugs without affecting the stable codebase.

  6. HEAD
    It is a pointer that indicates your current position in the repository. When you switch branches, HEAD moves to point to that branch.

  7. Merge
    The process to combine one branch to another is called merging.

  8. Clone
    As the name signifies, it makes a copy of a remote repository on the local machine.

  9. Pull
    It helps to fetch all the changes made by other on the remote repository and update the local repository with the changes.

  10. Push

    It is a process to commit your changes to the remote repository, making the changes available to others

Git's Three-Stage Architecture

Workflow:

  • Edit files in your working directory

  • Select the changes to commit by adding them to staging area

  • Commit the changes to your local repository

  • Share your changes with others by committing the changes to remote repository

Git Commands

Here comes the better part, the Git commands. Lets dive into them one by one.

  1. Configuration Commands
    Before you start using Git, you have to configure your identity.

     #Set your name
     git config --global user.name "your_name"
    
     #Set your email
     git config --global user.email "your.email@example.com"
    
     #Check your configuration
     git config --list
    
     #Set default branch name to 'main'
     git config --global init.defaultBranch main
    
  2. Creating and Cloning Repositories
    git init: To initialise git repository. .git subdirectory contains all the repository metadata.

     #Create a new directory and initialize Git
     mkdir new-project
     cd new-project
     git init
    

    git clone: Copy an existing remote repository

     #Clone a remote repository
     git clone https://github.com/username/repository.git
    
     #Clone into a specific folder
     git clone https://github.com/username/repository.git my-folder
    
  3. Checking Status and Changes
    git status: Check the state of your working directory, the files that were modified, files staged for commits, and the untracked files.

     #Check status 
     git status
    

    git diff: Get detailed view of change logs

     #Check unstaged changes
     git diff
    
     #Check staged changes
     git diff --staged
    
     #Compare two branches
     git diff branch1..branch2
    
  4. Adding and Committing Changes
    git add: Stage files for commit

     #add specific file
     git add filename.txt
    
     #add multiple files
     git add file1.txt file2.txt
    
     #add all changed files
     git add .
    

    git commit: Save staged changes to repository

     #Commit with inline message
     git commit -m "Add user authentication feature"
    
     #Commit with detailed message (opens editor)
     git commit
    
  5. Track History
    git log: View commit history

     #Standard log
     git log
    
     #Condensed one-line format
     git log --oneline
    
     #Show last 5 commits
     git log -5
    
     #Show commits with file changes
     git log --stat
    
     #Graphical representation
     git log --oneline --graph --all
    
     #Search commits
     git log --grep="bug fix"
    
  6. Branch management
    git branch: List, create, or delete branches

     #List all branches
     git branch
    
     #Create a new branch
     git branch new-feature
    
     #Delete a branch
     git branch -d added-feature
    
     #Force delete (even if not merged)
     git branch -D added-feature
    
     #Rename current branch
     git branch -m new-branch-name
    

    git checkout: Switch branches or restore files

     #Switch to existing branch
     git checkout new-feature
    
     #Create and switch to new branch
     git checkout -b new-feature
    
     #Restore a file to last committed state
     git checkout -- filename.txt
    
  7. Merging Changes
    git merge: Combine branches

     #switch to the branch you want to merge into
     git checkout main
    
     #then merge the feature branch
     git merge new-feature
    
  8. Repository Commands
    git remote: Manage remote repositories

     #List remote repositories
     git remote -v
    
     #Add a remote
     git remote add origin https://github.com/username/repo.git
    
     #Remove a remote
     git remote remove origin
    
     #Rename a remote
     git remote rename origin upstream
    

    git fetch: Download changes without merging

     #Fetch from default remote
     git fetch
    
     #Fetch from specific remote
     git fetch origin
    

    git pull: Fetch and merge changes

     #Pull from current branch remote
     git pull
    
     #Pull from specific branch
     git pull origin main
    

    git push: Upload local commits to remote

     #Push to remote repository
     git push origin main
    
     #Push and set upstream
     git push -u origin main
    
     #Push all branches
     git push --all
    
     #Force push (use with caution!)
     git push --force
    

    git stash: Temporarily save changes

     #Stash current changes
     git stash
    
     #List stashes
     git stash list
    
     #Apply most recent stash
     git stash apply
    
     #Apply and remove stash
     git stash pop
    
     #Stash with description
     git stash save "Working on feature"
    
  9. Undo Changes (or Life Saviour)

    git restore: Discard changes

     #Discard changes in working directory
     git restore filename.txt
    
     #Unstage a file
     git restore --staged filename.txt
    

    git revert: Create a new commit that undoes changes

     #Revert the last commit
     git revert HEAD
    
     #Revert a specific commit
     git revert commit-ID
    

Best Practice for Git Newbies

  • Commit Often: Make small changes frequently instead of huge changes. This helps to keep track and it is easy to revert changes.

  • Write Meaningful Commit Messages: It is easy to track the changes introduced when you or the collaborators visit the codebase.

  • Pull Before Push: Always pull the latest changes before pushing to avoid conflicts.

  • Use Branches: Commit new features in a branch and not directly in main.

  • Review Before Committing: Use git diff and git status to review changes before staging.

  • Don't Commit Sensitive Data: Never commit passwords, API keys, or personal information.

  • Use .gitignore: Create a .gitignore file to exclude files you don't want public to access (like node_modules/, .env, etc.)
    Example:

      #Dependencies
      node_modules/
    
      #Environment variables
      .env
    
      #OS files
      .DS_Store
      Thumbs.db
    
      #IDE files
      .vscode/
    

The Ultimate Cheat Sheet

#Setup
git config --global user.name "Name"
git config --global user.email "email@example.com"

#Creating repositories
git init
git clone <url>

#Basic workflow
git status
git add <file>
git commit -m "message"
git push
git pull

#Branching
git branch
git branch <name>
git checkout <branch>
git checkout -b <branch>
git merge <branch>

#History
git log
git log --oneline
git diff
git show

#Undoing
git restore <file>
git reset
git revert <commit>

#Remote
git remote add origin <url>
git push -u origin main
git fetch
git pull

Conclusion

Git is a powerful tool, and the moment you master it, your life becomes easy and it becomes an essential part of your workflow. The best way to learn Git is to get your hands dirty, make a project and struggle with Git, make mistakes. Start with basics: track changes, create snapshots, work in branches, and collaborate with others. Use git status to your strength to understand the flow of the process after every step.

Happy coding and may your gain the superpowers of Git soon !