Git is the one tool every DevOps engineer uses every day, and the one most people learn halfway. They learn add, commit, push and pull, then freeze the first time a merge conflicts, a commit lands on the wrong branch, or a rebase rewrites history they have already pushed. This cheat sheet covers the full working set: setup, the daily workflow, branching and merging, remotes, history inspection, and — the part that saves careers — safe undo.
Commands are grouped by the job you are doing, not alphabetically, because that is how you will look them up. Each group explains what the commands do, when to use them, and the mistake people make with them most often. Commands are current for Git 2.56.1, verified 5 Dec 2026, and the official Git reference documentation is the authority when a flag behaves differently than described here. If you want the concepts behind the commands — what a commit really is, how a branch is just a pointer — read our Git for DevOps engineers guide first, then keep this page open as your reference.
Setup and Configuration
Git is useless until it knows who you are, and it is dangerous until it is configured the way you expect. Every commit records an author name and email, so the first thing to do on a new machine is set your identity — otherwise your commits show up under the wrong name, or Git refuses to commit at all. Configuration lives in layers: system, global (your user account), and local (one repository), with each layer overriding the one above it.
git --version
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global core.editor "code --wait"
git config --global pull.rebase false
git config --list
git config user.email
git config --global user.name and user.email set your identity for every repository on the machine. init.defaultBranch main makes new repositories start on main instead of the older default master, which matches what GitHub and GitLab create today. core.editor chooses the editor Git opens for commit messages and rebase instructions; set it once and stop fighting the default.
git config --list shows every setting from every layer, which is how you find the stray setting that is causing strange behaviour — a common one is a global core.autocrlf value copied from a Windows setup guide that mangles line endings on Linux. git config user.email with no value reads a single setting, and adding --local scopes a change to the current repository: use that when a work repository needs your work email and your personal projects need another.
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.lg "log --oneline --graph --decorate --all"
git config --global credential.helper store
git config --global credential.helper cache
Aliases are shortcuts for commands you type constantly: git st instead of git status, git lg for a compact graph of history. Keep aliases short and memorable, and do not alias a destructive command to a short name — git reset --hard should never be two keystrokes away. Credential helpers decide how Git stores your login: cache keeps it in memory for a while, store writes it to disk in plain text. On a personal machine, prefer the operating system keychain helper; for automation, use a token with the smallest permissions it needs.
Starting a Repository: init and clone
Every Git workflow starts one of two ways: you create a repository from scratch, or you copy one that already exists. The two commands look similar and do very different things, and confusing them is the source of the classic beginner error of initializing a repository inside another repository.
git init
git init my-project
git clone https://github.com/example/my-project.git
git clone git@github.com:example/my-project.git
git clone --depth 1 https://github.com/example/my-project.git
git clone --branch release-2.0 https://github.com/example/my-project.git
git init creates a new, empty repository in the current directory, adding a hidden .git folder that holds all of Git’s data. Run it once, in a project that has no repository yet. Running it inside an existing repository does nothing harmful — Git notices and leaves the repository alone — but running it in your home directory by accident creates a repository that tries to track everything you own, which is a mess to unwind. git clone copies a remote repository to your machine, including its full history, and sets up a remote called origin pointing back at the source.
Clone over HTTPS to start, and switch to SSH once you have keys set up — SSH with a key agent means no password prompts. --depth 1 creates a shallow clone with only the latest commit, faster for large repositories and CI jobs, though you cannot inspect older history without fetching more. --branch clones a specific branch instead of the default. The mistake to avoid is cloning with the wrong URL protocol and then debugging authentication for an hour: check the URL with git remote -v before assuming Git is broken.
git remote -v
git remote add upstream https://github.com/original/my-project.git
git remote remove upstream
git remote rename origin upstream
git remote set-url origin git@github.com:example/my-project.git
git remote -v lists the remotes and their URLs, fetch and push separately — the first thing to check when a push goes to the wrong place. git remote add upstream is the standard move when you fork a repository: origin points at your fork, upstream points at the original, and you pull from upstream to stay current. set-url changes a remote’s address, which is how you switch a clone from HTTPS to SSH without re-cloning.
The Daily Workflow: Status, Add, Diff, Commit
Almost every Git session follows the same four steps: check what changed, stage what you want to keep, review it, and commit it. The commands are short, but the ideas behind them — the working tree, the staging area, the commit — are what make Git powerful.
git status
git status --short
git add app.py
git add .
git add -p
git add -A
git diff
git diff --staged
git diff --stat
git status is the command to run more often than feels necessary: it tells you which files changed, which are staged, which are untracked, and — helpfully — which command to run next. --short gives the same information in a compact two-column format, good for scripts and for a quick glance. git add moves changes into the staging area, the snapshot that the next commit will record. git add . stages everything in the current directory and below; git add -A stages everything in the whole repository, including deletions. git add -p is the precision tool: it walks you through each changed hunk and asks whether to stage it, so you can commit a bug fix and a refactor as two separate commits instead of one tangled one.
git diff shows unstaged changes — what is in your working files but not yet staged — while git diff --staged shows what is staged but not yet committed. The distinction matters: if you add a file and then edit it again, git diff shows only the new edit and git diff --staged shows only the staged version. git diff --stat gives a summary — files changed, lines added and removed — when you want the shape of a change without the detail.
git commit -m "Fix retry logic in deploy script"
git commit -am "Update health check endpoint"
git commit --amend
git commit --amend -m "Fix retry logic in deploy script"
git log --oneline
git log --oneline --graph --decorate --all
git show HEAD
git show 3e887ab --stat
git commit -m records the staged snapshot with a message. Write messages in the imperative mood — “Fix retry logic”, not “Fixed retry logic” — the convention every major project follows. git commit -am stages tracked files and commits in one step, skipping the staging area for files Git already knows about; it does not stage new, untracked files, which is a frequent surprise. git commit --amend folds new changes into the last commit or fixes its message, but it rewrites that commit, so never amend a commit you have already pushed.
git log --oneline prints one line per commit — hash, message — and adding --graph --decorate --all draws the branch structure, which is how you see where branches forked and merged. git show displays a commit’s full diff, and git show --stat shows only its file summary. The common mistake in this whole workflow is committing too rarely: a day of work in one commit is hard to review, hard to bisect, and hard to revert in part. Commit when a logical unit is done, not when the day is done.
Branches: Create, Switch, Merge, Rebase
A branch in Git is a lightweight pointer to a commit, not a copy of your files — creating one is instant, and switching branches just moves the pointer and updates your working files. That cheapness is the whole point: branches are how teams work in parallel without stepping on each other. The modern command is switch; checkout still works, but new users should learn switch first.
git branch
git branch -a
git branch feature/login
git switch feature/login
git switch -c feature/login
git checkout -b feature/login
git branch -m old-name new-name
git branch -d feature/login
git branch -D feature/login
git branch lists local branches, -a adds remote-tracking branches, and the asterisk marks the one you are on. git branch feature/login creates a branch but stays where you are; git switch -c feature/login creates it and moves to it in one step, which is what you want almost every time. git branch -m renames the current branch — useful when you realize the branch name has a typo or the wrong ticket number — and it updates the name cleanly as long as you have not pushed yet.
git branch -d deletes a branch, but only if it is fully merged, which is a safety net: Git refuses to delete work that exists nowhere else. -D forces the deletion, merged or not, and that is the flag to use with care — a forced delete of an unmerged branch destroys commits that exist only on that branch, recoverable only through the reflog. The most common branching mistake is working on the wrong branch: run git status or git branch before you start, and if you realize mid-work that you are on main, create the branch now with git switch -c — your uncommitted changes come with you.
git merge feature/login
git merge --no-ff feature/login
git merge --abort
git rebase main
git rebase --continue
git rebase --abort
git cherry-pick 3e887ab
git merge feature/login brings the branch’s commits into your current branch, creating a merge commit when the histories have diverged. --no-ff forces a merge commit even when a fast-forward would have been possible, which keeps the feature’s history visible as a unit — many teams prefer this for shared branches. A merge conflict means two people changed the same lines; Git marks the conflict in the file for you to resolve by hand. Edit the file, remove the markers, git add it, and commit. If the merge goes badly, git merge --abort returns everything to the state before the merge started.
git rebase main replays your branch’s commits on top of main, producing a linear history with no merge commit. Rebase produces a cleaner history, but it rewrites commits — never rebase commits other people have already pulled. During a rebase, conflicts are resolved one commit at a time, with git rebase --continue after each fix and git rebase --abort to give up entirely. git cherry-pick copies a single commit onto your current branch, which is how you pull one fix out of a branch without merging the whole thing. The mistake to avoid is rebasing a shared branch and then force-pushing it: everyone else’s copies of that branch are now out of date, and their next pull will be a mess.
Remotes: Fetch, Pull, Push and Tags
Git is distributed, which means your repository is a full copy, and the remote is just another copy that happens to be shared. fetch, pull and push are the three ways copies synchronize, and the difference between the first two is the one every Git user must understand: fetch downloads, pull downloads and merges.
git fetch
git fetch origin
git fetch --prune
git pull
git pull --rebase
git pull origin main
git push
git push -u origin feature/login
git push origin main
git push --force-with-lease
git fetch downloads new commits from the remote without touching your files or your branches — it is always safe, and it is how you look before you leap. git fetch --prune also removes remote-tracking branches for branches deleted on the server, which stops your branch list from filling up with ghosts. git pull fetches and then merges the remote branch into yours; git pull --rebase fetches and then rebases your commits on top of the remote ones, keeping history linear. For a shared branch with other people’s commits, prefer the plain pull or the rebase form your team has agreed on — mixing the two on the same branch creates duplicate merge commits and confused history.
git push sends your commits to the remote. The first push of a new branch needs -u origin feature/login, which sets the upstream tracking so that later pushes need only git push. git push --force-with-lease overwrites the remote branch, but only if nobody else has pushed since you last fetched — it is the safe form of force push, and the only form you should ever use on a shared branch. Plain --force overwrites unconditionally and can destroy other people’s commits; treat it as a last resort on a branch only you use.
git tag v1.2.0
git tag -a v1.2.0 -m "Release 1.2.0"
git tag -l "v1.*"
git push origin v1.2.0
git push --tags
git tag -d v1.2.0
git push origin --delete v1.2.0
Tags mark points in history, usually releases. A lightweight tag is just a name on a commit; an annotated tag carries a message, a date, and the tagger, and is the right choice for releases because it is a real Git object with its own identity. Tags are not pushed by a normal git push — push one tag by name, or all of them with --tags. The common mistake is creating a release tag locally, cutting a release from it in CI, and then discovering the tag never left your machine because nobody pushed it. In CI, tags are also how pipelines are triggered: a push of v1.2.0 can start a release workflow, as our GitHub Actions tutorial shows. Deleting a tag needs two steps — local delete, then push the deletion — or the tag comes back on the next fetch.
History and Inspection: Log, Show, Blame, Bisect
Git remembers everything, and the inspection commands are how you ask it questions: what changed, who changed it, when, and why. These are the commands that turn Git from a backup tool into a debugging tool, and they are the ones interviewers probe hardest, because they reveal whether you can investigate a codebase you did not write.
git log --oneline --graph --decorate --all
git log --since="2 weeks ago" --oneline
git log --author="Priya" --oneline
git log -p app.py
git log -S "retry" --oneline
git show 3e887ab
git show HEAD~2:app.py
git log with filters is a search engine for your project’s history. --since limits by date, --author by person, -p shows the full diff of each commit, and -S "retry" finds every commit that added or removed the string “retry” — the pickaxe search, and the fastest way to find when a piece of code appeared. git show 3e887ab displays one commit in full, and git show HEAD~2:app.py shows what a file looked like two commits ago, without changing anything. HEAD~2 means two commits before the current one, and HEAD~3 three — a compact way to refer to recent history without copying hashes.
git blame app.py
git blame -L 40,60 app.py
git bisect start
git bisect bad
git bisect good v1.1.0
git bisect reset
git grep "TODO" $(git rev-list --all)
git stash
git stash list
git stash pop
git stash apply
git stash drop
git blame annotates each line with the commit and author that last changed it — the starting point when a line of code looks wrong and you want to know why it exists. Limit it to a line range with -L so you are not scrolling through a whole file. git bisect finds the commit that introduced a bug by binary search: you mark a bad commit and a known-good one, and Git checks out the middle commit for you to test, halving the range each time until the culprit is found. It turns a hundred-commit search into about seven tests. Run git bisect reset when you are done, or you will be left on an old commit.
git stash shelves uncommitted changes so you can switch branches with a clean tree, and git stash pop brings the most recent stash back and deletes it from the list; apply brings it back without deleting it, and drop deletes one. Give a stash a message with git stash push -m "WIP: login form" when it might live more than an hour. git grep searches tracked files across history, which is how you find every place a function name or a secret appears without opening a dozen files.
Undoing and Recovering: Restore, Reset, Revert, Reflog
Undoing is where Git earns its reputation for being scary, and the fear comes from three commands that sound alike and do different things. The rule that makes them safe is simple: ask two questions before you undo — have I committed this, and have I pushed it? The answers decide which command is safe.
git restore app.py
git restore --staged app.py
git restore --staged --worktree app.py
git restore --source HEAD~1 app.py
git reset --soft HEAD~1
git reset --mixed HEAD~1
git reset --hard HEAD~1
git reset --hard origin/main
git restore is the safe undo for uncommitted work. git restore app.py discards your unstaged edits to that file; git restore --staged app.py unstages it while keeping your edits; --staged --worktree together discards both the staged and unstaged changes. git restore --source HEAD~1 app.py brings back the file as it was one commit ago. Restore never touches committed history, which is why it is the first undo to learn.
git reset moves the branch pointer backward, and its three modes decide what happens to your files. --soft moves the pointer but keeps everything staged, so the last commit is undone but its changes are ready to commit again — the right choice when you want to redo a commit message or split a commit. --mixed, the default, keeps the changes in your working files but unstages them. --hard discards everything: the commit, the staging, and the file changes. Check git status first: uncommitted work destroyed by a hard reset is gone unless the reflog can find it. git reset --hard origin/main is the nuclear reset: it makes your branch exactly match the remote, discarding local commits. Useful when a local branch is beyond saving; dangerous when it is not.
git revert 3e887ab
git revert --no-commit 3e887ab
git clean -fd
git clean -n
git reflog
git reset --hard HEAD@{2}
git revert is the safe undo for pushed work: instead of deleting the bad commit, it creates a new commit that undoes its changes. History stays honest, other people’s copies stay valid, and the revert itself can be reverted later if you change your mind. git clean -fd deletes untracked files and directories; -n is the dry run that shows what would be deleted — run it first, always, because clean has no undo of its own.
git reflog is the safety net under all of this. It records every move your branch pointer makes — commits, resets, rebases, checkouts — for about ninety days, and it can recover work that reset or a forced branch delete appeared to destroy. If you deleted a branch and regret it, git reflog shows the commit it pointed at, and git branch recovered 3e887ab brings it back. Our Git interview questions and answers go deeper on exactly these scenarios, because interviewers love asking what you do when history goes wrong.
Frequently Asked Questions
What is the difference between git fetch and git pull?
git fetch downloads new commits from the remote without changing your files or branches. git pull fetches and then merges the remote branch into yours. Fetch is always safe; pull can create merge conflicts. The habit to build is fetch first, look at what arrived, then merge or rebase deliberately.
Should I use git switch or git checkout?
Use git switch for moving between branches and git restore for discarding changes. They are the modern commands, split out of the old overloaded checkout, and they make your intent obvious. git checkout still works and you will see it in older tutorials, but learning the newer commands means fewer surprises.
When should I merge and when should I rebase?
Merge when you want to preserve the history of a feature branch as a unit, and when the branch is shared with other people. Rebase when you want a clean linear history on a branch only you use, such as a feature branch before opening a pull request.
How do I undo a commit I already pushed?
Use git revert, which creates a new commit that undoes the bad one’s changes. Do not use git reset --hard and force-push on a shared branch: it rewrites history that other people may already have, and their next pull will conflict. Revert keeps history honest and is safe for everyone.
What do I do when Git says my push was rejected?
It means someone else pushed to the branch first. Run git fetch, then git pull or git pull --rebase to bring their commits in, resolve any conflicts, and push again. If the rejection mentions a non-fast-forward update, that is the same situation: your branch is behind the remote, and you need to integrate their work before pushing yours.
Conclusion
Git’s command set looks large until you sort it by job: configure once, clone or init once, then repeat status, add, commit and push all day, with branching for parallel work and revert and reflog for the days things go wrong. The commands in this guide cover the working life of a DevOps engineer — from the first git init on a new project to the bisect that finds the commit that broke production.
The fastest way to make these commands stick is to use them under pressure, safely: create a throwaway repository, make a mess in it on purpose, and recover with the commands you have just read. That practice is what turns a cheat sheet into confidence, and confidence is what an interviewer is really testing when they ask about Git. The free Pro Git book goes deeper on the internals behind every command here.



