Git & Github in One Shot - The Ultimate Cheatsheet

    Git & Github in One Shot - The Ultimate Cheatsheet

    Git & GitHub in One Shot – The Ultimate Cheatsheet is a developer-focused quick reference that covers essential Git commands, branching strategies, workflows, and GitHub collaboration features. It helps developers track changes, manage repositories, resolve conflicts, and maintain a clean project history efficiently, making it ideal for beginners, students, and professionals alike.

    default profile

    Shreyash Gurav

    March 11, 2026

    13 min read

    Git & Github in one Shot - The Ultimate Cheatsheet

    Git is the industry-standard version control system that tracks changes in your code, enables collaboration, and protects your project history. GitHub builds on Git by providing cloud hosting, pull requests, and team collaboration tools. This cheat sheet gives you quick access to essential Git commands, workflows, and best practices without the fluff.

    Getting Started with Git#

    What is Git and Why Use It#

    Git is a distributed version control system that records snapshots of your files, allowing you to revert to previous states, compare changes, and collaborate without overwriting work. Unlike centralized systems, every developer has a complete copy of the project history locally. Git was created by Linus Torvalds in 2005 to manage the Linux kernel development efficiently.

    Key Points

    • Git tracks content changes, not just file names
    • Every clone is a full backup of the entire repository
    • Branching in Git is lightweight and inexpensive
    • Changes are stored as snapshots, not file differences
    • Git uses cryptographic hashing (SHA-1) to ensure data integrity

    Local vs Remote Repositories#

    A local repository exists on your machine and contains the complete project history with all branches. A remote repository is hosted on a server like GitHub, GitLab, or Bitbucket, enabling team collaboration and backup.

    Key Points

    • Local repos allow offline work and fast operations
    • Remote repos serve as the centralized source of truth
    • Changes move between repos through push and pull operations
    • You can connect multiple remotes to a single local repo
    • The default remote name is typically "origin"

    Git Installation and Configuration#

    Install Git from git-scm.com or using your package manager. After installation, configure your identity and preferences to ensure commits are properly attributed.

    # Set your global username and email git config --global user.name "Your Name" git config --global user.email "your.email@example.com" # Set your default branch name (Git 2.28+) git config --global init.defaultBranch main # Configure line endings (Windows vs Mac/Linux) git config --global core.autocrlf input # Mac/Linux git config --global core.autocrlf true # Windows # View all configurations git config --list

    Initializing and Cloning Repositories#

    Start version control in an existing project with git init or copy an existing remote repository with git clone. These are the entry points to any Git workflow.

    # Initialize a new repository in current folder git init # Initialize in a specific directory git init project-name # Clone an existing repository git clone <https://github.com/user/repo.git> # Clone into a specific folder name git clone <https://github.com/user/repo.git> my-folder # Clone with SSH (recommended for frequent pushes) git clone git@github.com:user/repo.git

    Basic Git Workflow#

    The fundamental workflow moves changes from your working directory to the staging area, then commits them to the repository history. This three-step process gives you control over what gets recorded.

    # Check status of your working directory git status # Add specific files to staging git add filename.txt # Add all changes in current directory git add . # Add all changes in the entire repository git add -A # Commit staged changes with a message git commit -m "Descriptive commit message" # View commit history git log # View condensed one-line history git log --oneline # See what's changed but not staged git diff # See staged changes git diff --staged

    Key Points

    • Working directory contains files you're editing
    • Staging area (index) is where you prepare your next commit
    • Commits are permanent snapshots with unique IDs
    • Always write clear commit messages explaining why, not what

    Ignoring Files with .gitignore#

    The .gitignore file tells Git which files or patterns to intentionally untrack, keeping your repository clean of temporary files, build artifacts, and sensitive information.

    Key Points

    • Place .gitignore in your repository root or subdirectories
    • Patterns support wildcards and negation with !
    • Already tracked files are not affected by ignore rules
    • Use global gitignore for OS-specific files
    • Common ignores: node_modules, .env, .DS_Store, build folders
    # Example .gitignore patterns # Dependencies node_modules/ vendor/ # Build outputs dist/ build/ *.exe *.dll # Environment files .env .env.local # IDE files .vscode/ .idea/ *.swp # OS files .DS_Store Thumbs.db

    Branching and Collaboration#

    Branching and Collaboration

    Branching in Git#

    Branches are lightweight pointers to specific commits, allowing parallel development without affecting the main codebase. Creating and switching branches is instantaneous because Git just moves a pointer.

    # List local branches git branch # List all branches including remote git branch -a # Create a new branch git branch feature-login # Switch to a branch git checkout feature-login # Create and switch in one command git checkout -b feature-login # Rename a branch git branch -m old-name new-name # Delete a branch (fully merged) git branch -d feature-login # Force delete unmerged branch git branch -D feature-login

    Key Points

    • Main branch is typically called main or master
    • Keep branches focused on single features or fixes
    • Delete branches after merging to keep clean history
    • Branch names should be descriptive: feature/, bugfix/, hotfix/

    Handling Merge Conflicts#

    A merge conflict occurs when Git cannot automatically reconcile differences between two branches. This usually happens when the same line of a file has been modified differently in two branches.

    Signs of a Conflict

    • Git shows messages like CONFLICT (content): Merge conflict in <file>
    • git status shows files as both modified

    Resolving Conflicts

    1. Open the conflicted file(s). Git marks conflicts like this:
    <<<<<<< HEAD Your changes here ======= Incoming changes here >>>>>>> feature-branch
    1. Edit the file to keep the correct version or combine changes.
    2. After fixing conflicts, mark as resolved:
    git add filename.txt
    1. Complete the merge:
    git commit # Or if rebasing git rebase--continue

    Best Practices

    • Pull frequently to minimize conflicts
    • Communicate with teammates about overlapping work
    • Keep branches small and focused
    • Use tools like git mergetool for complex merges

    Merging vs Rebasing#

    Both commands integrate changes from one branch into another, but they handle history differently. Merges preserve exact chronology while rebasing creates a linear history.

    AspectMergeRebase
    HistoryPreserves exact timeline with merge commitsCreates linear, cleaner history
    Commit IDsOriginal commits keep their IDsCommits get new SHA hashes
    ComplexitySimple, safe for shared branchesRiskier for public branches
    TroubleshootingEasier to see when changes happenedHarder to trace original context
    Use caseIntegrating completed featuresUpdating feature branch with main
    # Merge feature into main (stay on main branch) git merge feature-branch # Merge with no fast-forward (always creates merge commit) git merge --no-ff feature-branch # Rebase current branch onto main git checkout feature-branch git rebase main # Interactive rebase (squash, edit, reorder commits) git rebase -i HEAD~3

    Key Points

    • Never rebase public/shared branches
    • Merge when preserving context matters
    • Rebase for clean, linear history before pull requests
    • Interactive rebase helps clean up local commits

    Remote Repositories#

    Remotes are versions of your repository hosted on servers. They enable collaboration by allowing you to share commits and pull changes from teammates.

    # Add a remote repository git remote add origin <https://github.com/user/repo.git> # List configured remotes git remote -v # Fetch changes without merging git fetch origin # Fetch and merge (pull) from remote git pull origin main # Push local commits to remote git push origin main # Push and set upstream tracking git push -u origin main # Remove a remote git remote remove origin # Rename a remote git remote rename origin upstream

    Key Points

    • origin is the default name for your cloned remote
    • upstream often refers to the original repository in forks
    • Fetch is safe; pull combines fetch and merge
    • Always pull before pushing to avoid conflicts

    Collaborating with GitHub#

    GitHub transforms Git from a version control system into a complete collaboration platform. It provides the interface and tools that enable teams to review code, track work, and automate workflows around your Git repositories.

    Key Points

    • Pull requests are the core of code review and collaboration
    • Issues track bugs, feature requests, and tasks
    • Projects visualize work using Kanban boards
    • GitHub Actions automate testing and deployment
    • Code owners can be automatically requested for reviews

    Pull Request Workflow

    1. Push your feature branch to GitHub
    2. Open a pull request comparing your branch to main
    3. Add a clear description and request reviewers
    4. Discuss changes and push additional commits if needed
    5. Merge once approved and all status checks pass
    6. Delete the branch after merging to keep the repository clean

    Forking and Syncing with Upstream#

    Forking creates a personal copy of someone else's repository on GitHub. This is essential for open-source contributions where you don't have write access.

    Key Points

    • Forks are independent repositories under your account
    • Keep your fork synced to contribute clean pull requests
    • The original repo is typically called "upstream"
    • Never commit directly to upstream main
    # Add original repository as upstream remote git remote add upstream <https://github.com/original/repo.git> # Fetch upstream changes git fetch upstream # Checkout your local main git checkout main # Merge upstream changes into your main git merge upstream/main # Push updates to your fork git push origin main

    Viewing Commit History#

    Git's log provides powerful filtering and formatting options to navigate project history. Understanding history helps debug issues and understand code evolution.

    # Standard log with details git log # One line per commit git log --oneline # Graph view with branches git log --graph --oneline --all # Show last 3 commits git log -3 # Search commits by message git log --grep="fix bug" # Show commits by author git log --author="username" # Show files changed in each commit git log --stat # View specific file history git log -p filename.txt

    Key Points

    • Each commit has a unique 40-character SHA hash
    • Use -oneline for the 7-character short hash
    • Combine flags for custom views
    • git show displays a single commit's details

    Undoing Changes#

    Git provides multiple ways to undo changes depending on what stage they're in and whether you've shared them. Understanding the difference between reset, revert, and checkout is crucial.

    # Unstage a file (keep changes) git reset HEAD filename.txt # Discard working directory changes git checkout -- filename.txt # Restore file to previous commit state git restore filename.txt # Undo last commit, keep changes staged git reset --soft HEAD~1 # Undo last commit, unstage changes git reset HEAD~1 # Undo last commit, discard all changes git reset --hard HEAD~1 # Create new commit that undoes previous commit git revert HEAD # Revert a specific commit by hash git revert abc123

    Key Points

    • reset moves the branch pointer and optionally modifies working directory
    • revert creates a new commit that undoes changes (safe for shared history)
    • checkout or restore for working directory files
    • Never use -hard if you're unsure about losing changes

    Tagging and Releases#

    Tags mark specific points in history as important, typically for releases. They're like branch references that never move.

    Tag TypeDescriptionWhen to Use
    LightweightJust a pointer to a commitTemporary labels, personal markers
    AnnotatedFull object with message, author, datePublic releases, official versions
    # Create lightweight tag git tag v1.0.0 # Create annotated tag git tag -a v1.0.0 -m "Release version 1.0.0" # List all tags git tag # List tags matching pattern git tag -l "v1.*" # Push specific tag to remote git push origin v1.0.0 # Push all tags git push --tags # Delete local tag git tag -d v1.0.0 # Delete remote tag git push origin --delete v1.0.0 # Checkout tag (detached HEAD) git checkout v1.0.0

    Collaboration Best Practices#

    Effective collaboration requires clear conventions and communication. These practices prevent conflicts and keep history readable.

    Key Points

    • Write commit messages in imperative tense: "Fix login bug"
    • Pull before starting work to stay updated
    • Keep commits focused on single changes
    • Use feature branches for all changes
    • Review your own pull request before requesting reviews
    • Resolve conflicts locally before pushing
    • Communicate breaking changes in commit messages

    Branching Strategies#

    Different workflows suit different team sizes and release cycles. Choose the strategy that matches your deployment frequency and team structure.

    StrategyStructureBest ForComplexity
    Git Flowmain, develop, feature, release, hotfixLarge projects with scheduled releasesHigh
    GitHub Flowmain + feature branchesContinuous deployment, simple projectsLow
    Trunk-Basedshort-lived feature branches off mainCI/CD, multiple daily deploymentsMedium

    Git Flow

    • main always reflects production-ready state
    • develop integrates completed features
    • Release branches prepare for production
    • Hotfix branches patch production directly

    GitHub Flow

    • Anything in main is deployable
    • Create branches for features/fixes
    • Open pull requests for discussion
    • Deploy immediately after merging

    Trunk-Based Development

    • Small, frequent commits directly to main or short-lived branches
    • Feature flags hide incomplete work
    • Continuous integration runs on every commit
    • Releases are snapshots of main at any time
    Branching workflows side by side

    Stashing Changes and Applying Patches#

    Stash temporarily saves uncommitted changes when you need to switch contexts. It's like a clipboard for your working directory.

    # Save current changes to stash git stash # Save with a descriptive message git stash save "WIP: login feature" # List all stashes git stash list # Apply most recent stash (keep in stash) git stash apply # Apply and remove from stash git stash pop # Apply specific stash git stash apply stash@{2} # Create branch from stash git stash branch new-branch # Clear all stashes git stash clear

    Key Points

    • Stashes are stack-based (last in, first out)
    • Untracked files aren't stashed by default (use u)
    • Stashes are local only, never pushed
    • Use for quick context switches, not long-term storage

    Rewriting History#

    Sometimes you need to clean up commits before sharing them. Amend and interactive rebase let you modify local history, but never rewrite public commits.

    # Amend last commit (change message or add files) git commit --amend -m "Better commit message" # Add forgotten files to last commit git add forgotten-file.txt git commit --amend --no-edit # Interactive rebase last 3 commits git rebase -i HEAD~3 # Rebase from specific commit git rebase -i abc123 # Squash multiple commits into one (during rebase) # In rebase editor: change 'pick' to 'squash'

    Rebase Interactive Options

    • pick - use the commit
    • reword - change commit message
    • edit - modify commit content
    • squash - combine with previous commit
    • fixup - like squash but discard message
    • drop - remove commit
    Interactive rebase

    Git LFS for Large Files#

    Git LFS (Large File Storage) replaces large files with text pointers while storing the actual content on a remote server. This keeps repositories fast and clones small.

    Key Points

    • Install LFS separately: git lfs install
    • Track file types: git lfs track "*.psd"
    • LFS files are downloaded only when needed
    • Requires server support (GitHub, GitLab support LFS)
    • Great for binaries, assets, datasets, and media
    # Install LFS in repository git lfs install # Track file patterns git lfs track "*.zip" git lfs track "assets/**" # View tracked patterns git lfs track # List LFS files in repository git lfs ls-files # Migrate existing files to LFS git lfs migrate import --include="*.psd" --everything

    Security in Git and GitHub#

    Secure your code and access with proper authentication and repository protection. Never commit secrets, tokens, or passwords.

    MethodSetupUse CaseSecurity
    HTTPSUsername + tokenSimple setup, firewallsToken-based, 2FA support
    SSHGenerate key pairFrequent pushes, automationKey-based, very secure
    # Generate SSH key ssh-keygen -t ed25519 -C "your.email@example.com" # Add key to ssh-agent eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519 # View public key to add to GitHub cat ~/.ssh/id_ed25519.pub # Test SSH connection ssh -T git@github.com

    GitHub Security Features

    • Branch protection rules prevent direct pushes to main
    • Require pull request reviews before merging
    • Require status checks to pass
    • Dependabot alerts for vulnerable dependencies
    • Secret scanning detects committed credentials
    • Personal access tokens replace passwords for HTTPS 

    Workflow Summary#

    The complete Git workflow connects local changes through staging, commits, and branches to remote collaboration and deployment.

    Git workflow
    # Complete feature workflow example git checkout -b feature/new-dashboard git add . git commit -m "Add dashboard components" git push -u origin feature/new-dashboard # Open pull request on GitHub # Address review comments git add . git commit -m "Fix review feedback" git push # Merge when approved git checkout main git pull origin main git branch -d feature/new-dashboard

    Conclusion#

    Git and GitHub form the backbone of modern software development, enabling teams to collaborate efficiently while maintaining complete project history. This cheat sheet condenses years of best practices into a quick-reference format designed for daily use. Master these commands and workflows to work confidently whether you're solo coding or contributing to large open-source projects. Bookmark this guide, share it with your teammates, and return whenever you need to refresh your Git knowledge. If you found this useful, pass it along to fellow developers.

    Want to Master Spring Boot and Land Your Dream Job?

    Struggling with coding interviews? Learn Data Structures & Algorithms (DSA) with our expert-led course. Build strong problem-solving skills, write optimized code, and crack top tech interviews with ease

    Learn more
    Git
    Version Control
    GitHub
    GitLab
    BitBucket
    Was it helpful?

    Subscribe to our newsletter

    Read articles from Coding Shuttle directly inside your inbox. Subscribe to the newsletter, and don't miss out.