Prakhar Singh

The Ultimate Git Cheat Sheet & Command Reference

Cover Image for The Ultimate Git Cheat Sheet & Command Reference
Prakhar Singh
Prakhar Singh

Git is a free and open-source distributed version control system responsible for everything that happens locally on your computer. Whether you are a student or a professional, mastering these commands is essential for managing code history.

1. Setup & Configuration


Configure user information for all local repositories.

  • Set Username: git config --global user.name "[firstname lastname]" Sets the name identifiable for credit in version history.

  • Set Email: git config --global user.email "[valid-email]" Sets the email address associated with each history marker.

  • Enable Color: git config --global color.ui auto Sets automatic command line coloring for easy reviewing.

2. Initialization & Cloning


Start a new repository or get an existing one.

  • Initialize Repo: git init Initializes an existing directory as a Git repository (creates a hidden .git folder).

  • Clone Repo: git clone [url] Retrieves an entire repository from a hosted location via URL to your local storage.

3. Staging (The Index)


Prepare files for the next commit.

  • Stage Specific File: git add [file] Adds a file as it looks now to your next commit (stage).

  • Stage All Files: git add . Puts all files in the staging area.

  • Move/Rename & Stage: git mv [existing-path] [new-path] Changes an existing file path and stages the move immediately.

  • Remove & Stage: git rm [file] Deletes the file from the project and stages the removal for commit.

4. Committing


Save your staged changes to the history.

  • Commit: git commit -m "[descriptive message]" Commits your staged content as a new snapshot. The -m flag lets you provide the message inline.

5. Status & History


Inspect the state of your project.

  • Check Status: git status Shows modified files in the working directory and staged files for the next commit.

  • View Commit History: git log Shows the entire commit history for the currently active branch.

  • Note: Press q to exit the log view.

  • File Specific History: git log --follow [file] Shows the commits that changed a file, even across renames.

  • Visualize Branch History: git log --stat -M Shows commit logs with indications of paths that moved.

6. Undoing Changes


Revert or unstage changes.

  • Unstage File: git reset [file] Unstages a file while retaining the changes in the working directory.

  • Alternative: git restore --staged [file].

  • Discard Local Changes: git checkout [file] Removes files that are not committed yet (reverts to last commit state).

  • Reset to Commit: git reset --hard [commit] Clears the staging area and rewrites the working tree from the specified commit.

7. Branching


Isolate work in different contexts.

  • List Branches: git branch Lists your branches; a * appears next to the currently active branch.

  • Create Branch: git branch [branch-name] Creates a new branch at the current commit.

  • Switch Branch: git checkout [branch-name] Switches to another branch and checks it out into your working directory.

  • Create & Switch: git checkout -b [branch_name] Creates a new branch and switches to it immediately.

  • Modern Switch Command: git switch [branch] A dedicated command to switch branches.

8. Merging & Rebasing

Integrate changes from one branch to another.

  • Merge Branch: git merge [branch] Merges the specified branch's history into the current one.

  • Rebase Branch: git rebase [branch] Applies any commits of the current branch ahead of the specified one (rewrites history for a linear path).

9. Remote Repositories


Connect your local repo to the world.

  • Add Remote: git remote add [alias] [url] Adds a git URL as an alias (commonly origin).

  • View Remotes: git remote -v Displays all repo URLs attached to the current working folder.

  • Remove Remote: git remote remove origin or git remote rm origin Removes the linked URL from the git folder.

10. Syncing (Push & Pull)


Sync your local changes with a remote repository.

  • Fetch Changes: git fetch [alias] Fetches down all the branches from that Git remote without merging.

  • Pull Changes: git pull Fetches and merges any commits from the tracking remote branch into your current branch.

  • Equivalent to: git fetch + git merge.

  • Push Changes: git push [alias] [branch] Transmits local branch commits to the remote repository branch.

  • Force Push: git push origin [branch] -f Forces the push. Required if you have rewritten history (e.g., used git reset) on a branch that was already pushed.

11. Stashing (Temporary Storage)


Temporarily store modified, tracked files to switch branches without committing.

  • Stash Changes: git stash Saves modified and staged changes to a stack.

  • Stash Specific Files: git stash push <path/to/file> Stashes only the changes in the specified files.

  • List Stashes: git stash list Lists the stack-order of stashed file changes.

  • Apply Stash (Keep): git stash apply or git stash apply stash@{n} Applies the most recent stash (or a specific index n) but keeps it in the stash list.

  • Pop Stash (Apply & Drop): git stash pop Writes working changes from the top of the stash stack and removes them from the list.

  • Drop Stash: git stash drop Discards the changes from the top of the stash stack.

  • Clear All: git stash clear empties the entire stash.

12. Inspection & Diffing


Compare changes between commits, staging, and branches.

  • Diff Working Directory: git diff Shows the difference of what is changed but not staged.

  • Diff Staging Area: git diff --staged Shows the difference of what is staged but not yet committed.

  • Diff Branches: git diff branchB...branchA Shows the diff of what is in branchA that is not in branchB.

  • Compare Commits: git log branchB..branchA Shows the commits on branchA that are not on branchB.

  • Show Object: git show [SHA] Shows any object (commit, tag, etc.) in Git in a human-readable format.

13. Protocols (SSH vs HTTPS)


Choose how to connect to GitHub.

  • HTTPS: git clone https://github.com/username/repository.git Easier setup, but requires credentials (password/token) for every interaction.

  • SSH: git clone git@github.com:username/repository.git More secure; uses a Public Key (on GitHub) and Private Key (on your machine). No passwords needed for daily use.

14. Fork & Pull Workflow


The standard workflow for contributing to open-source projects.

  1. Fork: Click the "Fork" button on the GitHub repository to copy it to your account.

  2. Clone: git clone [your-fork-url].

  3. Add Upstream: git remote add upstream [original-repo-url] (Links the original repo to track updates).

  4. Sync Fork:

  • git fetch --all --prune (Get latest branches).
  • git reset --hard upstream/main (Reset local main to match original).
  • git push origin main (Update your GitHub fork).
  1. Create PR: Push your feature branch to your origin, then click "Compare & Pull Request" on GitHub.

15. Debugging & Tools


Advanced commands for finding issues and managing files.

  • Search Text: git grep [pattern] Prints lines matching a pattern in tracked files.

  • Find Bug: git bisect Uses binary search to find the specific commit that introduced a bug.

  • Manage Tags: git tag Create, list, delete, or verify a tag object signed with GPG.

16. Ignoring Files


Prevent Git from tracking specific files.

  • Local Ignore: Create a file named .gitignore and add patterns:

  • logs/ (Ignore directory)

  • *.notes (Ignore extension)

  • Global Ignore: git config --global core.excludesfile [file] Sets a system-wide ignore pattern for all local repositories.

17. Git Bash Utilities


Helpful terminal commands when using Git Bash.

  • List Hidden Files: ls -la Shows hidden files (like .git).

  • Detailed List: ls -lrta Lists files with details, sorted by reverse modification time.

  • Copy/Paste: Use Ctrl+Insert to copy and Shift+Insert to paste (standard Ctrl+C/V does not work).

  • Reset Screen: reset Resets the Git Bash terminal.

18. Getting Help


Access manual pages directly from the terminal.

  • General Help: git --help.

  • All Commands: git help -a.

  • Specific Command: git help <command>.

  • Workflows: git help workflows.

19. SSH Keys Explained


  • What is an SSH Key? A pair of cryptographic keys used for secure authentication without passwords.

  • Public Key: Shared with GitHub. It encrypts data and verifies your identity.

  • Private Key: Stored securely on your computer. It decrypts data and signs requests. Never share this.

  • How it Works: When you connect, GitHub uses your uploaded public key to challenge your machine, which answers using the private key.

20. Conceptual Differences


Clarifying commonly confused terms.

  • Clone vs. Fork:

  • Git Clone: Downloads a repository from the internet to your local machine's storage.

  • Git Fork: Creates a copy of a repository on your GitHub account. It does not download anything to your computer.

  • Merge vs. Rebase:

  • Merging: Takes the output of two branches and combines them. History remains "true" to what happened when.

  • Rebasing: Moves your entire branch to begin at the tip of another branch (e.g., main). It rewrites history to make it look linear.

21. Best Practices & Workflow Tips


Some advice to avoid common pitfalls.

  • Never Commit to Main: Always create a separate branch for your work (git checkout -b feature-name). This prevents your commits from getting stacked directly on the stable codebase.

  • Sync Before You Start: Before creating a new branch or starting work, always sync your local repository with the remote to ensure you are working on the latest version (git pull or git fetch).

  • Force Push with Caution: If you use commands that rewrite history (like git reset or git rebase) on code that is already pushed, you must use git push origin <branch> -f. Be careful as this can overwrite work for others.


Thanks For Reading!