Skip to content

Git Basics

Git is a distributed version control system that tracks changes in files, enabling collaboration and history management for projects. Here’s a concise guide to learn Git.

  • Repository (Repo):
    A project folder tracked by Git. Contains all files and their history.
  • Commit:
    A snapshot of changes at a point in time (with a unique ID and message).
  • Branch:
    An independent line of development (default: main or master).
  • Remote:
    A cloud-hosted repo (e.g., GitHub, GitLab and even in a local folder) for team collaboration.
  • Staging Area:
    A “preview” space where changes are prepared before committing.
CommandDescription
git initCreates a new repo in the current folder.
git clone <url>Downloads a remote repo to your machine.
git add <file>Stages changes for commit.
git add .Stages all files in the current folder.
git commit -m "Message"Saves staged changes to history.
git statusShows unstaged/staged changes.
git logDisplays commit history.
  • Create branch:
    Terminal window
    git checkout -b new-branch-name # Create and switch to a new branch
  • Switch branch:
    Terminal window
    git switch branch-name # Switch to target branch
    git checkout branch-name # Switch to target branch
  • Merge branches:
    Terminal window
    git merge branch-name # Merge <branch-name> changes into the current branch
  • Resolve conflicts:
    Manually edit conflicted files, then git add and git commit.
CommandPurpose
git remote add origin <url>Links local repo to a remote.
git push -u origin mainUploads commits to remote (set upstream).
git pullFetches remote changes and merges locally.
git fetchDownloads remote changes without merging.
  • Unstage a file:
    Terminal window
    git reset HEAD <file>
  • Discard unstaged changes:
    Terminal window
    git checkout -- <file>
  • Revert a commit:
    Terminal window
    git revert <commit-id> # Creates a new commit undoing changes
  1. Commit often: Small, logical changes with clear messages.
  2. Branch early: Use branches for features/fixes.
  3. Pull before push: Avoid merge conflicts.
  4. Use .gitignore: Exclude files (e.g., logs, binaries).
  5. Review changes:
    Terminal window
    git diff # Unstaged changes
    git diff --staged # Staged changes
Terminal window
# Clone a repo
git clone https://github.com/user/project.git
# Create a new branch <dev> adn switch into it
git checkout -b dev
# Make changes, then stage & commit
git add index.html
git commit -m "Up date index"
# Push to remote branch
# (Create a new remote branch if there's no dev branch in remote repo.)
git push origin dev:dev

Git’s power lies in its flexibility—start with these basics, then explore advanced features as needed!