Skip to main content

TalentNep

Tutorial

The Complete Git Guide: Commands, Branching & Workflow


The Complete Git Guide: From First Commit to Advanced Workflows

If you write code, sooner or later you will need Git. It is the tool that quietly sits behind almost every software project on the planet, tracking every change, protecting your work, and letting teams build the same codebase without stepping on each other's toes. This guide walks through Git from the ground up, so whether you have never typed git init or you just want a solid refresher, you will find something useful here.

1. Introduction to Git

Git is a free, open-source distributed version control system designed to handle everything from small personal projects to massive codebases with thousands of contributors, quickly and efficiently.

Git was created in 2005 by Linus Torvalds, the same person behind the Linux kernel. At the time, the Linux development community needed a tool that could track changes across a huge, fast-moving codebase without relying on a single central server. Existing tools were too slow or too fragile for that scale, so Torvalds built Git in a matter of weeks, and it has since become the default choice for version control worldwide.

Every developer, regardless of language or specialty, benefits from learning Git. It protects your code from accidental loss, gives you a complete history of every decision made in a project, and makes teamwork possible without email attachments named final_v2_reallyfinal.zip.


2. What Is Version Control?

A Version Control System (VCS) is software that records changes to files over time, so you can recall specific versions later. It matters because software is never really "finished" — it evolves constantly, and every change needs to be traceable, reversible, and shareable.

Life Without Version Control

  • Lost code — a single deleted file or crashed laptop can erase weeks of work
  • No backup — there is no safety net if something breaks
  • No collaboration — two people editing the same file leads to overwritten work
  • Difficult debugging — there is no way to see what changed or when a bug was introduced

Life With Version Control

  • Track changes — every edit is recorded with who made it and why
  • Restore previous versions — roll back to any point in history
  • Team collaboration — multiple people can work in parallel safely
  • Code history — a searchable timeline of the entire project

3. Types of Version Control Systems

Local Version Control

The earliest approach — a simple database on your own machine tracking file changes. Advantage: simple and requires no network. Disadvantage: no collaboration and a single point of failure if your disk dies.

Centralized Version Control (CVCS)

Tools like SVN and Perforce store the full history on one central server, and everyone checks out files from it. Advantage: easier to administer and understand. Disadvantage: if the server goes down, nobody can commit, and there's no way to work fully offline.

Distributed Version Control (DVCS)

Git and Mercurial represent this modern approach: every contributor has a full copy of the entire repository, history included. Advantage: resilience, speed, and offline work. Disadvantage: a steeper learning curve for newcomers.


4. Why Choose Git?

Git dominates the industry for good reason. Here's what makes it stand out:

  • Fast — most operations happen locally, so they're near-instant
  • Lightweight — efficient storage even for large histories
  • Open source — free to use and continuously improved by the community
  • Secure — every piece of history is checksummed with SHA hashes
  • Distributed — every clone is a full backup
  • Offline support — commit, branch, and browse history without internet
  • Powerful branching and merging — built for parallel, non-linear development
  • Free to use — no licensing costs, ever

5. Git Architecture

Understanding Git's architecture makes everything else click into place. Your project data moves through four conceptual layers:

1. Working Directory — the actual files you see and edit on disk
2. Staging Area (Index) — a holding zone for changes you're about to commit
3. Local Repository — your committed history, stored in the hidden .git folder
4. Remote Repository — a shared copy hosted elsewhere, like GitHub

Changes flow in one direction: you edit files in the working directory, stage the ones you want to save into the staging area, commit them into your local repository, and finally push them up to a remote repository so others can see them.


6. How Git Works Internally

Git doesn't store changes as simple diffs the way older systems do. Instead, it thinks in snapshots — every commit is a complete picture of your project at that moment, with unchanged files simply linked to their previous version rather than duplicated.

Each commit forms a node in your commit history, and every object in Git — a file, a folder, a commit — is identified by a unique SHA hash, a 40-character fingerprint generated from its content. Change even one character, and the hash changes completely, which is what makes Git's history tamper-evident.

Git's Core Objects

  • Blob — the raw content of a file
  • Tree — a directory listing that points to blobs and other trees
  • Commit — a snapshot pointer with metadata (author, message, parent commit)
  • Tag — a permanent, human-friendly label pointing to a specific commit

7. Installing Git

Git installation differs slightly depending on your operating system:

  • Windows — download the installer from the official Git website and run through the setup wizard
  • Mac — install via Xcode Command Line Tools, or simply run brew install git if you use Homebrew
  • Linux — use your package manager, for example sudo apt install git on Debian-based distributions

Once installed, confirm it worked with:

git --version

8. Git Configuration

Before your first commit, tell Git who you are. This information gets attached to every commit you make.

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

To review every setting currently applied:

git config --list

9. Creating Your First Repository

There are two ways to start working with a Git repository:

git init

This turns the current folder into a brand-new, empty Git repository — perfect for starting a project from scratch.

git clone <repository-url>

This downloads an existing repository, complete with its full history, onto your machine.

The difference in short: init creates something new, while clone copies something that already exists elsewhere.

10. The Git Workflow

Here is the everyday cycle you'll repeat constantly:

Working Directory → git add → Staging Area
Staging Area → git commit → Local Repository
Local Repository → git push → Remote Repository

11. Git Basic Commands

These are the commands you'll reach for daily:

  • git init — start a new repository
  • git clone — copy an existing repository
  • git status — see what's changed, staged, or untracked
  • git add — move changes into the staging area
  • git commit — save staged changes to history
  • git log — view commit history
  • git diff — see exact line-by-line differences
  • git restore — discard changes in the working directory
  • git rm — remove a file from the repository
  • git mv — rename or move a tracked file

12. Understanding Git Status

Every file in your project sits in one of these states at any given time:

Untracked → a new file Git doesn't know about yet
Tracked → Git is watching this file for changes
Modified → the file has changed since the last commit
Staged → the change is marked, ready to be committed
Committed → the change is safely saved in history

13. Git Commit

A commit is a saved snapshot of your project, along with a message explaining why the change was made. Good commit messages are one of the most underrated skills in software development — future you (and your teammates) will thank you.

Commit Message Examples

Bad:

fixed

Good:

Fix login validation for empty password

A good commit message is specific, written in the present tense, and explains what changed and often why.


14. Git Log

The git log family of commands lets you explore project history in different levels of detail:

git log

Shows the full commit history with author, date, and message.

git log --oneline

Condenses each commit to a single line — great for a quick overview.

git log --graph

Adds an ASCII graph showing how branches diverged and merged.


15. Git Branching

A branch is simply a movable pointer to a commit, letting you diverge from the main line of development and work independently. Branches exist so multiple features, fixes, or experiments can progress at the same time without interfering with each other.

  • Creating a branch: git branch feature-login
  • Switching branches: git switch feature-login or git checkout feature-login
  • Deleting a branch: git branch -d feature-login
  • Renaming a branch: git branch -m new-name

Most teams follow a branching strategy — an agreed convention for how branches are named and merged — to keep things predictable as the team grows.


16. Branching Workflow

A typical project organizes its branches by purpose:

  • Main branch — the stable, production-ready code
  • Feature branch — isolated work on a new capability
  • Bug fix branch — targeted fixes for known issues
  • Release branch — final polishing before a version ships
  • Hotfix branch — urgent fixes applied directly to production

Git Flow is a popular formalized model built around these branch types, giving teams a clear, repeatable process for shipping software.


17. Git Merge

Merging brings the work from one branch into another. There are two common types:

Fast-Forward Merge

Happens when the target branch hasn't moved since you branched off — Git simply slides the pointer forward, no new commit needed.

Three-Way Merge

Happens when both branches have diverged — Git creates a new merge commit combining both histories.

Pros: preserves full history and context of parallel work. Cons: can introduce conflicts that require manual resolution.


18. Merge Conflicts

Conflicts happen when Git can't automatically decide how to combine changes — usually because the same lines were edited differently on both branches. Git marks the conflicting sections directly in the file:

<<<<<<< HEAD
your version of the code
=======
their version of the code
>>>>>>> feature

To resolve a conflict, edit the file to keep the correct content, remove the conflict markers, then stage and commit the result. Best practice: pull frequently and keep branches short-lived to minimize the chances of conflicts piling up.


19. Git Rebase

Rebase replays your commits on top of another branch's latest changes, producing a cleaner, linear history instead of a merge commit.

Merge vs. Rebase: merge preserves exact history including branch points, while rebase rewrites history to look as if you'd branched off later.

Advantages: a clean, easy-to-follow project history. Disadvantages: rewriting history is risky on shared branches, since it changes commit hashes. Use rebase on your own local branches, and avoid it on branches others are already using.


20. Git Stash

Sometimes you need to switch tasks without committing half-finished work. Stash temporarily shelves your changes so your working directory becomes clean again.

git stash
git stash pop
git stash list

Stash is perfect for quick context switches — like an urgent bug report interrupting a feature you're halfway through.


21. Git Tags

Tags mark specific points in history as important, usually for releases.

  • Annotated tags — store extra metadata like author, date, and message; recommended for releases
  • Lightweight tags — simply a pointer to a commit, with no extra data

Create, list, and delete tags with:

git tag v1.0.0
git tag
git tag -d v1.0.0

22. Undoing Changes

Git offers several ways to undo work, and picking the right one matters:

  • Restore — discard changes in the working directory
  • Reset — move the branch pointer, optionally changing staged and working files
  • Revert — create a new commit that undoes a previous one, safe for shared history
  • Checkout — switch branches or restore specific files from history

In short: reset rewrites history, revert adds to history, and restore only touches your working files.


23. Git Reset in Detail

  • Soft reset — moves the commit pointer but keeps changes staged
  • Mixed reset — moves the pointer and unstages changes, but keeps them in your working directory (this is the default)
  • Hard reset — moves the pointer and discards all changes completely
git reset --soft HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1

Use hard reset with caution — it permanently deletes uncommitted work.


24. Git Remote

A remote is a version of your repository hosted elsewhere, like GitHub.

git remote add origin <url>
git remote remove origin
git remote rename origin upstream
git remote -v

25. Git Push

Pushing sends your local commits to a remote repository.

git push origin main

A force push (git push --force) overwrites remote history with your local version. Avoid force pushing to shared branches like main — it can silently erase teammates' work.


26. Git Pull

git pull is really two commands combined: it fetches new commits from the remote, then merges (or rebases, with git pull --rebase) them into your current branch.


27. Git Fetch

Fetch downloads new commits and branches from the remote without merging them into your work, giving you a chance to review changes first. Fetch vs. pull: fetch is the safe, look-before-you-leap option, while pull merges immediately.

git fetch origin

28. GitHub, GitLab, Bitbucket, and Azure DevOps

GitHub is a cloud platform for hosting Git repositories, adding features like pull requests, issue tracking, and CI/CD on top of Git itself. Remember: Git is the tool, GitHub is a service that hosts projects using it.

Platform Known For
GitHub Largest community, strong open-source ecosystem
GitLab Built-in CI/CD, popular for self-hosting
Bitbucket Tight integration with Jira and Atlassian tools
Azure DevOps Deep integration with Microsoft's enterprise stack

29. Connecting Git With GitHub

Once you've created a repository on GitHub, connect your local project to it:

git remote add origin https://github.com/username/repo.git
git push -u origin main

You can authenticate over HTTPS (using a username and personal access token) or SSH (using a key pair, no password prompt needed).


30. SSH Keys

SSH keys let you authenticate with GitHub securely, without typing a password every time.

ssh-keygen -t ed25519 -C "you@example.com"

Add the generated public key to your GitHub account settings, then confirm the connection works:

ssh -T git@github.com

31. Pull Requests (PRs)

A Pull Request is a request to merge your branch into another, typically main. It exists to enable code review — teammates read your changes, leave comments, and approve or request adjustments before anything gets merged. Once approved, the PR is merged, closing the loop between writing code and shipping it safely.


32. Git Ignore

The .gitignore file tells Git which files or folders to never track — things like dependencies, build artifacts, and secrets that shouldn't live in version control.

node_modules/
.env
dist/

Best practice: add a .gitignore file at the very start of a project, before your first commit, to avoid accidentally committing files you'll regret later.


33. Git Aliases

Aliases let you shorten long, frequently used commands:

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.st status
git config --global alias.cm commit

Now git st works exactly like git status, saving keystrokes all day long.


34. Git Hooks

Hooks are scripts Git runs automatically at specific points in your workflow:

  • Pre-commit — runs before a commit is finalized, often used for linting or tests
  • Post-commit — runs right after a commit completes
  • Pre-push — runs before code is pushed, useful for running a final test suite

Teams use hooks to enforce quality gates automatically, without relying on developers to remember every step manually.


35. Git Best Practices

  • Make small, focused commits rather than giant ones
  • Write meaningful commit messages
  • Pull before you push to avoid unnecessary conflicts
  • Never commit secrets like API keys or passwords
  • Use feature branches instead of working directly on main
  • Keep the repository clean with a solid .gitignore
  • Review before merging — always request a second pair of eyes

36. Common Git Mistakes to Avoid

  • Committing large files — bloats the repository permanently
  • Force pushing without warning teammates
  • Working directly on main instead of a feature branch
  • Poor commit messages like "update" or "fix stuff"
  • Ignoring conflicts instead of resolving them carefully

37. Git Interview Questions

If you're preparing for a technical interview, expect questions across a range of difficulty:

  • Beginner: What is Git? What's the difference between Git and GitHub?
  • Intermediate: Explain the difference between merge and rebase. What is a detached HEAD?
  • Advanced: How does Git store data internally? What is the purpose of the reflog?
  • Scenario-based: How would you recover a deleted branch, or resolve a conflict across five files at once?

38. Git Cheat Sheet

The commands you'll use most, all in one place:

git init
git clone
git add
git commit
git push
git pull
git fetch
git merge
git rebase
git stash
git branch
git checkout
git switch
git restore

39. A Real-World Git Workflow

1. Developer creates a new branch
2. Writes code
3. Commits changes
4. Pushes the branch to the remote
5. Opens a Pull Request
6. Team performs code review
7. Branch is merged into main
8. Code is deployed

40. Advanced Git Topics

Once the basics feel natural, these topics unlock even more control:

  • Cherry-pick — apply a specific commit from one branch onto another
  • Bisect — binary-search through history to find which commit introduced a bug
  • Reflog — a safety net recording every move of HEAD, even ones erased from normal history
  • Squash — combine multiple commits into one, cleaner unit
  • Interactive rebase — reorder, edit, or squash commits before finalizing them
  • Detached HEAD — a state where you're viewing a commit outside any branch
  • Git submodules — nest one repository inside another
  • Git LFS — handle large binary files without bloating the main repository
  • Sparse checkout — check out only part of a large repository
  • Worktrees — check out multiple branches into separate folders simultaneously
  • Signed commits — cryptographically verify who authored a commit
  • Git internals, objects, and pack files — the low-level storage engine behind everything above
  • Garbage collection — Git's process for cleaning up unreachable data

41. Git in CI/CD

Git is the trigger point for most modern deployment pipelines. Tools like GitHub Actions, Jenkins, GitLab CI, and Azure Pipelines watch for events — a push, a merged PR, a new tag — and automatically run tests, build artifacts, and deploy code. This turns every commit into a potential deployment, with no manual steps in between.


42. Security in Git

  • Secrets — never commit passwords, tokens, or keys; use environment variables instead
  • SSH keys — protect repository access with key-based authentication
  • GPG signing — cryptographically prove a commit really came from you
  • Protected branches — block direct pushes to critical branches like main
  • Code owners — require specific people to approve changes to sensitive files

43. Frequently Asked Questions

Is Git free?

Yes. Git is completely free and open source under the GNU General Public License.

Can Git work offline?

Yes. Since every clone contains the full history, you can commit, branch, and browse logs without any internet connection.

What is HEAD?

HEAD is a pointer to your current position in history — usually the tip of the branch you're on.

What is origin?

origin is simply the default name Git gives to the remote repository you cloned from.

What is upstream?

upstream typically refers to the original repository you forked from, as opposed to your own copy.

Can I undo a push?

Yes, though carefully. You can revert the commit and push that, or force-push a corrected history if you're certain no one else has pulled it yet.

What is detached HEAD?

It's a state where you've checked out a specific commit instead of a branch — any new commits you make won't belong to a branch unless you create one.

What's the difference between git switch and git checkout?

git switch is a newer, more focused command for changing branches, while git checkout is older and handles both branch switching and file restoration, which made it a bit overloaded.


44. Conclusion

Git can feel intimidating at first, with its own vocabulary and a command for seemingly everything. But at its core, it comes down to a simple loop: edit, stage, commit, push. Everything else — branching, merging, rebasing, hooks — exists to make that loop safer and more powerful as your projects and teams grow.

Key takeaways:

  • Git protects your work and gives you a full, searchable history
  • Branching lets teams build in parallel without conflict
  • Small commits and clear messages pay off enormously over time
  • Platforms like GitHub add collaboration on top of what Git already does well

The best way to learn Git is to use it daily. Start a small project, commit often, experiment with branches, and don't be afraid of mistakes — almost everything in Git can be undone. From here, explore official documentation, interactive tutorials, and real open-source projects to keep building your confidence.