Git Commands Cheatsheet: 50 Daily Essentials for Pro Developers
In the modern landscape of software engineering, version control is not just a convenience; it is the heartbeat of the development lifecycle. Whether you are a solo developer managing a side project or part of a massive distributed team at a tech giant, Git is the industry standard that ensures code integrity, enables collaboration, and provides a safety net against catastrophic errors.
However, the sheer breadth of the Git ecosystem can be overwhelming. While most developers are comfortable with git push and git pull, the true power of Git lies in its deeper, more nuanced commands. Mastering these allows you to navigate complex merge conflicts, clean up messy commit histories, and recover "lost" work with surgical precision.
This Git Commands Cheatesheet is designed to be your definitive reference. We have categorized 50 essential commands into logical workflows, moving from basic setup to advanced debugging and repository maintenance.
The Foundation: Setting Up Your Environment
Before you can track changes, you must establish a repository and configure your identity. This stage is critical because Git relies heavily on your configuration to attribute commits correctly.
Initializing and Cloning Repositories
Every Git journey begins with either creating a new history or adopting an existing one.
git init: This is the starting point. It initializes a new, empty Git repository in your current directory, creating the hidden.gitfolder that tracks all metadata.git clone <url>: Used to copy an existing repository from a remote server (like GitHub or GitLab) to your local machine. This command also automatically sets up a remote namedorigin.git clone --depth 1 <url>: A "shallow clone" that only pulls the latest commit. This is incredibly useful for CI/CD pipelines where you don't need the entire historical baggage of a massive project.
Configuring Your Identity
Git needs to know who you are for the git log to be meaningful.
git config --global user.name "Your Name": Sets the name attached to your commit much like a digital signature.git config --global user.email "your@email.com": Sets the email address. Ensure this matches your GitHub/GitLab profile to maintain consistent contribution graphs.git config --list: Displays all current configurations. If you are ever unsure why a certain behavior is occurring, this is the first command to run.git config --global core.editor <editor>: Sets your default text editor (e.g., Vim, Nano, or VS Code) for writing commit messages.
Managing Ignored Files
One of the most vital aspects of a clean repository is ensuring that temporary files, build artifacts, and sensitive credentials never enter the version history. This is where the gitignore tool becomes indispensable.
git clean -f: Removes untracked files from your working directory. Use with extreme caution.git clean -fd: Removes untracked files and directories.git ls-files --others --exclude-standard: Shows you which files are currently being ignored by your.gitignorerules.
The Core Workflow: From Working Directory to Repository
The Git architecture is built on three distinct areas: the Working Directory (your actual files), the Staging Area (the "index" where you prepare changes), and the Repository (the permanent history). Understanding how to move data between these stages is the essence of Git mastery.
The Staging Process
Staging allows you to craft "atomic commits"—small, logical units of work that are easy to review and revert.
git status: The most frequently used command. It tells you which files are modified, which are staged, and which are untrbed.git add <file>: Moves a specific file from the working directory to the staging area.git add .: Stages all changes in the current directory and subdirectories.git add -p: (Pro Tip) The "patch" mode. This allows you to interactively review "chunks" of a file and decide whether to stage them. This is the secret to creating clean, professional commits.git add --all: Stages everything, including deletions.
Committing Changes
A commit is a snapshot of your project at a specific point in time.
git commit -m "message": Creates a commit with a single-line description.git commit -a: Automatically stages all modified files and commits them. Note: This does not include new (untracked) files.git commit --amend: The "oops" command. It allows you to add forgotten changes to the most recent commit or simply fix a typo in the commit message.git commit --allow-empty: Creates a commit even if no changes were made. Useful for triggering CI/CD pipelines.
Inspecting and Comparing Changes
Before you push your code, you must verify that what you are sending is actually what you intended.
git diff: Shows the differences between your working directory and the staging area.git diff --staged: Shows the differences between the staging area and your last commit.- /code/git-command/ (Reference): For a deeper dive into specific flag usage, always refer to a dedicated Git command reference to avoid mistakes.
git diff <branch1> <branch2>: Compares the differences between two different branches.
Branching Mastery: Navigating Parallel Universes
Branching is Git's "killer feature." It allows you to diverge from the main line of development to experiment, fix bugs, or build features without breaking the stable production code.
Creating and Navigating Branches
git branch: Lists all local branches in your repository.git branch <name>: Creates a new branch but does not switch to it.git checkout <branch>: Switches your working directory to the specified branch.git switch <branch>: A newer, more intuitive command introduced to separate "switching branches" from "restoring files."git checkout -b <name>: A shortcut that creates a new branch and immediately switches to it.git switch -c <name>: The modern equivalent ofcheckout -b.git branch -d <name>: Deletes a branch that has already been merged.git branch -D <name>: Force-deletes a branch, even if it contains unmerged work. Use with caution!
Merging and Integrating Changes
Once a feature is complete, it must be integrated back into the main codebase.
git merge <branch>: Merges the specified branch into your current active branch. /git merge --abort: If a merge results in a massive conflict that you aren't ready to handle, this command returns your repository to the state it was in before the merge started.git rebase <branch>: Re-writes your commit history by moving your current branch's commits to the tip of the target branch. This creates a much cleaner, linear history compared to a merge.git rebase -i <commit-hash>: (Interactive Rebase) The "master" command. It allows you to squash, rename, or reorder commits. This is how you turn a messy "work-in-progress" history into a polished series of professional commits.git cherry-pick <commit-hash>: Allows you to pick a single, specific commit from another branch and apply it to your current branch. Perfect for porting a bug fix from a development branch to a production branch without merging the whole feature.
Remote Collaboration: Syncing with the World
In a distributed environment, your local repository is only one piece of the puzzle. You must constantly synchronize with a "remote" (the single source of truth, usually on GitHub, GitLab, or Bitbucket).
Managing Remotes
git remote -v: Shows the URLs of the remote repositories linked to your local project.git remote add origin <url>: Connects your local repository to a new remote server.git remote rename origin upstream: Useful when you are working on a fork and need to distinguish between your fork and the original repository.
Fetching, Pulling, and Pushing
git fetch <remote>: Downloads all the history and branches from the remote, but does not change your local working files. It is a "safe" way to see what others have done.git pull: The combination ofgit fetchfollowed bygit merge. It updates your current branch with the latest changes from the remote.git pull --rebase: A cleaner way to pull. It fetches the remote changes and then rebases your local work on top of them, avoiding unnecessary "merge commits."git push origin <branch>: Uploads your local branch commits to the remote repository.git push -u origin <branch>: The-u(upstream) flag links your local branch to the remote branch. After running this once, you can simply typegit push.git push --force: DANGER. Overwrites the remote history with your local history. Never use this on shared branches (likemain) as it will break the workflow for everyone else.
The Safety Net: Undoing Mistakes and Recovering Work
Even senior developers make mistakes. Git's greatest strength is its ability to act as a time machine.
Resetting and Reverting
The distinction between reset and revert is one of the most common points of confusion for intermediate developers.
| Command | Scope | Impact on History | Best Use Case |
|---|---|---|---|
git reset --soft |
Staging Area | Keeps changes in Staging | You committed too early and want to add more files to the same commit. |
git reset --mixed |
Working Directory | Keeps changes in Working Dir | You want to "unstage" files but keep the code you wrote. |
git reset --hard |
Entire Repository | Destructive - Deletes changes | You made a total mess and want to return to a known good state. |
git revert <hash> |
Entire Repository | Creates a new commit | You need to undo a mistake on a public/shared branch without rewriting history. |
The Power of Stashing
Sometimes, you are in the middle of a complex feature, and a critical bug fix comes in. You aren't ready to commit your messy, unfinished code, but you need to switch branches.
git stash: Takes your uncommitted changes (both staged and unstaged) and "hides" them in a temporary storage area, leaving you with a clean working directory.- ally
git stash list: Shows all the stashed changes you have currently stored. git stash pop: Takes the most recent stash, applies it to your current branch, and removes it from the stash list.git stash apply: Likepop, but keeps the changes in the stash list (safer if you want to apply the same changes to multiple branches).git stash drop: Deletes a specific stash from your list.
Advanced Recovery
git reflog: The "Ultimate Undo." Git keeps a log of every single time theHEADpointer moves (even during resets or deletes). If you accidentally deleted a branch or did ahard reseton the wrong commit,reflogallows you to find the commit hash of where you used to be.git fsck: A low-level tool used to check the integrity of the Git filesystem and find "dangling" objects that might be recoverable.
Advanced Inspection and Debugging
When a bug appears in a codebase with thousands of commits, you need more than just git status.
git log --oneline: Provides a condensed, one-line-per-commit view of your history.git log --graph --all --decorate: The "Visualizer." It renders an ASCII graph in your terminal showing how branches have diverged and merged.git show <commit-hash>: Displays the full details and the actual code diff of a specific commit.git blame <file>: Shows line-by-line who last modified a file and in which commit. Essential for finding the context behind a specific logic change.git grep "pattern": Searches your entire repository for a specific string of text, much like the Unixgrepcommand, but aware of Git's tracking.git bisect: The "Binary Search" for bugs. You mark a "good" commit and a "bad" commit, and Git automatically checks out commits in between to help you pinpoint exactly which commit introduced the regression.
Practical Workflow Example: The Feature Branch Workflow
To tie all these commands together, let's look at a standard professional workflow for developing a new feature.
Scenario: You are tasked with adding a "Login" feature to a project.
- Update your local main branch:
git checkout maingit pull origin main - Create a new feature branch:
git switch -c feature/login-system - Start coding and stage your progress:
(Edit files...)
git statusgit add src/auth.py - Commit your work incrementally:
git commit -m "Add basic authentication logic" - Work continues, but you need to fix a bug on main immediately:
git stash(Saves your unfinished login work)git checkout maingit pull origin main(Fix bug, commit, and push...)git push origin main - Return to your feature and restore your work:
git switch feature/login-systemgit stash pop - Finalize the feature and prepare for a Pull Request:
git add .git commit -m "Complete login system with JWT support"git push -u origin feature/login-system - Merge the feature (after PR approval):
git checkout maingit merge feature/login-systemgit push origin main
FAQ
1. What is the difference between Git and GitHub? Git is the local version control software that tracks changes in your files. GitHub is a cloud-based hosting service that manages Git repositories, providing a UI, Pull Request workflows, and collaboration tools.
2. How do I resolve a merge conflict?
When a conflict occurs, Git marks the disputed area in the file with <<<<<<<, =======, and >>>>>>>. You must manually edit the file to decide which code to keep, remove the markers, then run git add <file> and git commit.
3. Is it safe to use git push --force?
Almost never on a shared branch. It overwrites the remote history. If a teammate has pushed work that you don't have locally, force will delete their work forever. Use git push --force-with-lease instead, as it will fail if the remote has changed since your last fetch.
4. Why should I use a .gitignore file?
Without a .gitignore, you will accidentally commit node_modules, .env files containing secrets, .DS_Store files, and build logs. This bloats the repository size and creates massive security risks.
5. What does "Detached HEAD" mean?
A "Detached HEAD" state occurs when you checkout a specific commit instead of a branch. In this state, any new commits you make won't belong to any branch and will be lost if you switch away. To fix it, simply create a new branch: git switch -c my-new-branch.
6. How can I find a deleted file in Git?
If the file was part of a previous commit, you can use git log --all -- <path_to_file> to find the commit where it was removed, and then use git checkout <commit_hash> -- <file_path> to recover it.
Conclusion
Mastering the Git Commands Cheatsheet is a journey of moving from reactive usage to proactive management. By moving beyond simple commits and embracing tools like git rebase, git stash, and git bisect, you transform Git from a simple backup tool into a powerful engine for software engineering excellence. Remember, the goal isn't to memorize all 50 commands, but to understand the workflow they enable. Keep this guide handy, practice the advanced commands in a safe environment, and you will soon find yourself navigating complex codebases with unparalleled confidence.