← Back to Notes

Git Basics

What is Git?

Git is a Version Control System (VCS) for tracking changes in computer files and coordinating work among multiple developers.

  • Distributed version control: Every developer has a complete copy of the project history.
  • Coordinate work between devs: Enables multiple people to work on the same project simultaneously.
  • Track change details: Maintains a complete history of what changed, when, and by whom.
  • Revert to old versions: Easily go back to previous states of your project.
  • Local & remote repos: Work offline and sync with remote servers when needed.

What Does "Distributed" Mean?

Unlike centralized version control systems, Git's distributed nature means:

  • You keep your files in a repository on your local machine.
  • You synchronize your repository with a repository on a server.
  • If you move from one machine to another, you can pick up changes by syncing with the server.
  • If your partner uploads changes to your files, you can pick those up by syncing to the server.

Key Concepts of Git

  • Keep track of code history: Git maintains a complete timeline of your project.
  • Takes "snapshots": Git saves the entire state of your project at specific points in time.
  • Visit any snapshot: You can view or restore any previous version of your project.
  • Stage files before committing: Git uses a staging area to let you choose exactly what changes to include.

Git Local View

In your local copy of Git, files can exist in three states:

  • Committed: Files are safely stored in your local repository.
  • Modified: Files have been changed but not yet committed (working directory).
  • Staged: Modified files marked to go into your next commit (staging area).
Git workflow diagram showing working directory, staging area, and local repository

Using Git

Basic Commands

Here are the fundamental Git commands you'll use most often:

# Initialize a new Git repository
git init
# Add file(s) to staging area
git add {file}
# Check status of working tree
git status
# Commit changes in staging area
git commit
# Push to remote repository
git push
# Pull latest from remote repository
git pull
# Clone repository into a new directory
git clone

Git Availability

  • Git is available on all operating systems from git-scm.com.
  • Git is free and open source. 😄
  • Most modern IDEs have built-in Git support.

Creating a New Git Repository

# Initialize the current folder as a Git repository
git init

This command creates a folder named ".git" which:

  • Contains all the internal files necessary for Git to function.
  • Should never be manually modified.
  • Is hidden by default in most file explorers.

After initializing, set up your personal information:

# Configure Git with your information
git config --global user.name "First Last"
git config --global user.email "email@example.com"
# View current configuration
git config --list

The .gitignore File

Create a .gitignore file to specify files and folders that Git should not track:

# Example .gitignore content
*.log
node_modules/
.env
.DS_Store
*.tmp

Cloning an Existing Git Repository

# Clone a repository
git clone "url" [localDirectoryName]
# Example
git clone https://github.com/username/repo.git my-project

This creates a local directory containing:

  • A working copy of all files from the repository.
  • A .git directory with the full project history.
  • An automatic connection to the remote repository.

Git Commands Overview

Git commands workflow diagram

Add & Commit Files

The typical workflow for saving changes:

# Add specific files to staging area
git add Hello.java Goodbye.java
# Add all files in current directory
git add .
# Add all files with specific extension
git add *.js

After staging files, commit them to the repository:

# Commit with a message
git commit -m "Fix bug #22: resolve login issue"
# Commit with detailed message
git commit -m "Add user authentication

Implement login functionality.
Add password hashing.
Create user session management."

Checking Repository Status

# Check current status
git status
# Check status in short format
git status -s
# See what changes are staged
git diff --cached
# See what changes are unstaged
git diff

Viewing History

# View commit history
git log
# View compact history
git log --oneline
# View history with graph
git log --graph --oneline --all
# View specific number of commits
git log -5

Branching & Merging

Working with Branches

Branches allow you to work on different features or experiments without affecting the main codebase:

# Create a new branch
git branch feature-login
# Switch to the branch
git checkout feature-login
# Create and switch to branch in one command
git checkout -b feature-login
# Or using newer syntax
git switch -c feature-login
# List all branches
git branch
# List all branches including remote
git branch -a

Merging Branches

# Switch to main branch
git checkout main
# Merge feature branch into main
git merge feature-login
# Delete branch after merging
git branch -d feature-login
# Force delete branch
git branch -D feature-login

Branch Best Practices

  • Use descriptive names: feature-user-auth, bugfix-login-error.
  • Keep branches small: Focus on one feature or fix per branch.
  • Merge regularly: Don't let branches diverge too far from main.
  • Delete merged branches: Keep your branch list clean.

Remote Repositories & GitHub

GitHub Setup

GitHub is a cloud-based hosting service for Git repositories. It provides collaboration features, issue tracking, and project management tools.

# Link a remote repository to local repo
git remote add origin https://github.com/username/repo.git
# Verify remote connection
git remote -v
# Change remote URL
git remote set-url origin https://github.com/username/new-repo.git

Pushing & Pulling Changes

# Push changes to remote repository
git push origin main
# Push and set upstream branch
git push -u origin main
# Pull changes from remote repository
git pull origin main
# Fetch changes without merging
git fetch origin

Common Workflows

Daily Workflow

# Start of day: get latest changes
git pull origin main
# Create feature branch
git checkout -b feature-new-component
# Work on your changes...
# Add and commit as needed
git add .
git commit -m "Add new component functionality"
# Push feature branch
git push origin feature-new-component
# Create pull request on GitHub
# After review and approval, merge and cleanup
git checkout main
git pull origin main
git branch -d feature-new-component

Collaboration Workflow

# Fork repository on GitHub
# Clone your fork
git clone https://github.com/yourusername/project.git
# Add upstream remote
git remote add upstream https://github.com/original/project.git
# Keep your fork updated
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

Common Issues & Solutions

Merge Conflicts

# When merge conflicts occur
git merge feature-branch
Auto-merging file.txt
CONFLICT (content): Merge conflict in file.txt
# Resolve conflicts manually in your editor
# Look for conflict markers: <<<<<<<, =======, >>>>>>>
# After resolving conflicts
git add file.txt
git commit -m "Resolve merge conflicts"

Undoing Changes

# Unstage files
git reset HEAD file.txt
# Discard working directory changes
git checkout -- file.txt
# Undo last commit (keep changes)
git reset --soft HEAD~1
# Undo last commit (discard changes)
git reset --hard HEAD~1
# Revert a commit (safe for shared repositories)
git revert abc1234

Useful Git Aliases

# Set up helpful aliases
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.lg "log --oneline --graph --all"
# Now you can use shorter commands
git st    # instead of git status
git co    # instead of git checkout
git lg    # instead of git log --oneline --graph --all

Git Cheat Sheet

Here's a comprehensive reference for the most commonly used Git commands:

Repository Setup

git init                     # Initialize repository
git clone {url}              # Clone remote repository
git remote add origin {url}  # Add remote repository

Basic Operations

git status                   # Check repository status
git add {file}               # Stage file
git add .                    # Stage all files
git commit -m "{message}"    # Commit with message
git push                     # Push to remote
git pull                     # Pull from remote

Branching Commands

git branch                   # List branches
git branch {name}            # Create branch
git checkout {branch}        # Switch branch
git checkout -b {branch}     # Create and switch branch
git merge {branch}           # Merge branch
git branch -d {branch}       # Delete branch

History & Inspection

git log                      # View commit history
git log --oneline            # Compact history
git diff                     # Show unstaged changes
git diff --cached            # Show staged changes
git show {commit}            # Show specific commit

Undoing Commands

git reset HEAD <file>        # Unstage file
git checkout -- {file}       # Discard changes
git reset --soft HEAD1      # Undo commit, keep changes
git reset --hard HEAD1      # Undo commit, discard changes
git revert {commit}          # Safely undo commit

📄 Git Education Cheat Sheet

📥 Download PDF