The Ultimate Git Cheat Sheet & Command Reference



Table of Contents
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 autoSets automatic command line coloring for easy reviewing.
2. Initialization & Cloning
Start a new repository or get an existing one.
-
• Initialize Repo:
git initInitializes an existing directory as a Git repository (creates a hidden.gitfolder). -
• 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-mflag lets you provide the message inline.
5. Status & History
Inspect the state of your project.
-
• Check Status:
git statusShows modified files in the working directory and staged files for the next commit. -
• View Commit History:
git logShows the entire commit history for the currently active branch. -
Note: Press
qto 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 -MShows 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 branchLists 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 (commonlyorigin). -
• View Remotes:
git remote -vDisplays all repo URLs attached to the current working folder. -
• Remove Remote:
git remote remove originorgit remote rm originRemoves 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 pullFetches 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] -fForces the push. Required if you have rewritten history (e.g., usedgit 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 stashSaves 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 listLists the stack-order of stashed file changes. -
• Apply Stash (Keep):
git stash applyorgit stash apply stash@{n}Applies the most recent stash (or a specific indexn) but keeps it in the stash list. -
• Pop Stash (Apply & Drop):
git stash popWrites working changes from the top of the stash stack and removes them from the list. -
• Drop Stash:
git stash dropDiscards the changes from the top of the stash stack. -
• Clear All:
git stash clearempties the entire stash.
12. Inspection & Diffing
Compare changes between commits, staging, and branches.
-
• Diff Working Directory:
git diffShows the difference of what is changed but not staged. -
• Diff Staging Area:
git diff --stagedShows the difference of what is staged but not yet committed. -
• Diff Branches:
git diff branchB...branchAShows the diff of what is in branchA that is not in branchB. -
• Compare Commits:
git log branchB..branchAShows 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.gitEasier setup, but requires credentials (password/token) for every interaction. -
• SSH:
git clone git@github.com:username/repository.gitMore 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.
-
• Fork: Click the "Fork" button on the GitHub repository to copy it to your account.
-
• Clone:
git clone [your-fork-url]. -
• Add Upstream:
git remote add upstream [original-repo-url](Links the original repo to track updates). -
• 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).
- • 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 bisectUses binary search to find the specific commit that introduced a bug. -
• Manage Tags:
git tagCreate, 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
.gitignoreand 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 -laShows hidden files (like.git). -
• Detailed List:
ls -lrtaLists files with details, sorted by reverse modification time. -
• Copy/Paste: Use
Ctrl+Insertto copy andShift+Insertto paste (standard Ctrl+C/V does not work). -
• Reset Screen:
resetResets 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 pullorgit fetch). -
• Force Push with Caution: If you use commands that rewrite history (like
git resetorgit rebase) on code that is already pushed, you must usegit push origin <branch> -f. Be careful as this can overwrite work for others.
Thanks For Reading!