Git Cheat Sheet: Commands, Branching Strategies, Undo and Pull Requests Explained

Table of Contents

Git is free version control software that records every change to a project’s files, so you can see what changed, undo mistakes and work with other people without overwriting each other. The Git commands you will use most are git status, git add, git commit, git switch, git pull and git push. This Git cheat sheet gives those and more than 40 others with working examples. It also covers how to undo any commit, which branching strategy suits a solo developer, a weekly-release team or an open-source project, every term you’ll meet, the common mistakes, and Git in Visual Studio Code and with AI assistants such as Claude and ChatGPT.

By Linda Garrould · Updated 1 November 2026 · Written for Git 2.40 and later, with older equivalents noted

Key takeaways

  • Most days need six commands: status, add, commit, switch, pull and push.
  • To undo something already shared, use git revert; git reset is only for commits nobody else has.
  • Branching strategy should match how often you release: trunk-based or GitHub flow for continuous delivery, release branches for a weekly rhythm, forks for open source.
  • It’s called a pull request because you are asking the maintainers to pull your work into their repository.
  • AI assistants are good at explaining Git and drafting commit messages, but never let one push to main or run a destructive command unchecked.

New to Git? This page doubles as a beginner’s Git tutorial. Read these four sections in order: what Git is, setting up, your first project and how to undo. Then keep the rest as a reference.

On this page: 20 essential commands · Undo · Error messages · Mistakes · Full reference · Branching strategies · VS Code · AI · Glossary · Git vs SVN · FAQ · PDF

Git cheat sheet: the 20 commands you’ll use most

These twenty commands cover almost everything you will do in a normal week. The full reference, with examples and warnings, comes further down.

CommandWhat it does
git initStart tracking the current folder
git clone URLCopy a repository and its history
git statusWhat has changed and what is staged
git add fileStage a change (git add . for everything)
git commit -m "Message"Save the staged changes as a snapshot
git log --oneline --graphCompact history
git diffChanges you haven’t staged yet
git switch -c nameCreate a branch and move to it
git switch mainMove to another branch
git branch -m new-nameRename the current branch
git branch -d nameDelete a merged branch
git merge nameMerge a branch into the current one
git pullFetch and merge others’ changes
git pushSend your commits to the shared copy
git stash / git stash popPut work aside, then bring it back
git restore fileThrow away unstaged edits to a file
git reset --soft HEAD~1Undo the last commit, keep the changes
git revert <hash>Undo a commit that is already shared
git cherry-pick <hash>Copy one commit onto this branch
git tag -a v1.2.0 -m "Release"Mark a release
Cover of the Ultimate Git Cheat Sheet A5 mini-ebook

Free download: the Ultimate Git Cheat Sheet (A5 PDF)

The essentials of this page as an A5 mini-ebook you can print or read on screen: the commands, the undo table, branching strategies with diagrams, the glossary, the common mistakes, VS Code shortcuts and safe ways to use AI, with a pin-up survival card on the back.

Download the PDF (36 pages, free, no sign-up)

Edition 1 · November 2026. Print at A5, or two pages to a sheet of A4. Free to print and share for non-commercial use, including in schools, colleges and user groups, under the CC BY-NC-ND 4.0 licence: credit IT Management 101, don’t sell it and don’t share altered versions. The QR code inside brings you back here for the latest edition.

Share it with someone learning Git:LinkedInFacebookXWhatsAppEmail

Get an email when I update it. I’ll let you know when a new edition is out, plus the occasional practical IT guide. Unsubscribe any time.

What is Git, and why do you need it?

Git is a version control system: software that keeps the complete history of a set of files, normally a software project’s source code. Every time you commit, Git saves a snapshot of the project along with who made the change, when and why. You can compare any two versions, go back to any earlier one, and work on several changes at once on separate branches before combining them.

Git working areasEdits start in the working tree, git add moves them to the staging area, git commit saves them in the local repository, and git push sends them to the remote. git pull brings others’ commits back.Where your changes live in GitWorking treethe files you editStaging areayour next commitLocal repositoryyour saved commitsRemoteGitHub, GitLab…git addgit commitgit pushgit pull (fetch others’ commits + merge)
Where your changes live: your files, the staging area, your local history and the shared copy.
  • You can undo anything. Every committed version is kept, so a bad change is a revert away, not a lost afternoon.
  • You can work in parallel. Each change gets its own branch; half-finished work never disturbs the version customers use.
  • Teams don’t overwrite each other. Git merges everyone’s changes and flags the rare clash for a person to decide.
  • You know why the code is the way it is. Each line can be traced to the commit, and the message, that introduced it.
  • It’s the industry standard. Almost every software job, open-source project, deployment pipeline and AI coding tool assumes Git.
  • It isn’t only for code. Documentation, configuration, infrastructure scripts and website content all benefit from history and review.

Linus Torvalds wrote Git in April 2005, in a matter of weeks, after the Linux kernel project lost its free licence for the commercial tool BitKeeper. He designed it for speed, for very large projects and for thousands of contributors working in parallel. Junio Hamano took over as maintainer that July and still leads it. The name is British slang for an unpleasant person: Torvalds joked that he names all his projects after himself, first Linux, now git.

Git vs GitHub: what’s the difference?

Git is the tool; GitHub is a place to host it. Git runs on your computer and works without any internet connection. GitHub, GitLab, Bitbucket and Azure DevOps are online services that store a shared copy of your repository and add what teams need around it: pull requests, code review, issue tracking, permissions and automated builds. You can use Git with none of them, or with all of them.

Setting up Git and starting a project

Install Git, tell it who you are, then either start a new repository with git init or copy an existing one with git clone. On Linux, install it with sudo apt install git (Debian, Ubuntu) or sudo dnf install git (Fedora, Red Hat); new to the terminal? See the Linux commands cheat sheet. On a Mac, typing git offers to install Apple’s command-line tools; on Windows, install Git for Windows, which includes Git Bash. Check with git --version; at the time of writing the latest release is 2.56, from September 2026.

Run these once per computer:

CommandWhat it does
git config --global user.name "Priya Shah"Your name on every commit
git config --global user.email "priya@example.co.uk"Your email; match your hosting account
git config --global init.defaultBranch mainCall the first branch main
git config --global core.editor "code --wait"Use VS Code for commit messages (or nano). On a Mac, first add the code command: see Git in VS Code
git config --global pull.rebase falsegit pull merges rather than stopping when branches diverge

Connect to GitHub or GitLab with an SSH (Secure Shell) key rather than a password. Run ssh-keygen -t ed25519 -C "priya@example.co.uk" (Azure DevOps accepts only RSA keys: ssh-keygen -t rsa -b 4096), then paste the contents of the .pub file into your account’s SSH keys page. Test it with ssh -T git@github.com.

Cloning with an https:// address instead? Your account password won’t work: GitHub stopped accepting passwords for Git in August 2021. Git for Windows and GitHub Desktop include Git Credential Manager, which signs you in through the browser; otherwise create a personal access token on the hosting site and paste it when Git asks for a password.

Your first project, step by step

  1. Create the project and the repository
    mkdir invoice-tool && cd invoice-tool
    git init
  2. Tell Git what to ignore, before anything else (in Git Bash, macOS or Linux; in PowerShell, create .gitignore in your editor)
    printf 'node_modules/\n.env\n*.log\n' > .gitignore
  3. Add your first files and commit
    git add .
    git commit -m "Initial commit"
  4. Create an empty repository on your hosting service (don’t add a README or licence), then connect and push
    git remote add origin git@github.com:priya/invoice-tool.git
    git branch -M main
    git push -u origin main
  5. From now on, the daily loop
    git switch -c feature/pdf-export
    # edit, test...
    git add .
    git status
    git commit -m "Add PDF export"
    git push -u origin feature/pdf-export

.gitignore: keep the wrong files out

A .gitignore file lists what Git should never track. Put it in place before your first commit: dependency folders such as node_modules/, build output, logs, editor settings and, above all, .env files and anything holding passwords or keys. GitHub publishes ready-made templates for most languages at github.com/github/gitignore. If a file is already tracked, adding it to .gitignore isn’t enough: run git rm --cached file too and commit that. Colleagues who pull it will have the file deleted from their copy, so warn them, and back up a .env file first.

How to undo a commit in Git (and almost anything else)

To undo the last commit and keep the work: git reset --soft HEAD~1. HEAD~1 means one commit before where you are now; HEAD~3 would be three. If that commit is already pushed, run git revert HEAD instead.

How you undo a commit depends on one question: has anyone else got it yet? If you haven’t pushed, you can rewrite your own history with git reset or git commit --amend. If you have, add a new commit that reverses it with git revert, so nobody else’s copy is disturbed. Find what happened in the left-hand column:

What happenedCommandWatch out
Edited a file and want the last committed version backgit restore fileYour edits are gone for good
Staged something by mistakegit restore –staged fileYour edits stay in the file
Last commit’s message is wrong, or a file is missing from itgit commit –amendNot yet pushed only
Undo the last commit, keep the workgit reset –soft HEAD~1Not yet pushed only
Undo the last commit and unstage everythinggit reset HEAD~1Same as –mixed; edits stay in your files
Throw away the last commit and every uncommitted editgit reset –hard HEAD~1Destructive: check git status first
Make my branch match the remote exactly, discarding local commits and editsgit fetch, then git reset –hard origin/mainDestructive: copy anything you want to keep onto another branch first
Undo a commit that is already pushedgit revert <hash>Safe: adds a new commit
Undo a merge that is already pushedgit revert -m 1 <merge-hash>-m 1 keeps the branch you merged into. Merging the same branch again later won’t bring the changes back; revert the revert first
Committed to main instead of a branch (not pushed)git switch -c new-branch, then git branch -f main origin/mainYour commit stays on new-branch and main goes back to match the remote; uncommitted edits are untouched
Deleted a branch or lost commitsgit reflog, then git switch -c rescue <hash>Act within 30 days
Pushed a password or keyRevoke or change it immediatelyRemoving it from history is not enough

Git error messages decoded

Git’s error messages are precise but terse. These are the ones you are most likely to meet, quoted as Git prints them, with what they mean and what to do.

Git saysIt meansDo this
Your branch is ahead of 'origin/main' by 1 commitYou have commits that aren’t on the remote yet.git push
Your branch is behind 'origin/main' by 2 commitsOthers have pushed work you don’t have.git pull
Updates were rejected because the remote contains work that you do not have locallySomeone pushed first.git pull, fix any conflicts, then git push. Never –force to make it go away
fatal: refusing to merge unrelated historiesThe remote was created with its own first commit, usually a README.Once: git pull origin main –allow-unrelated-histories, then git push
error: src refspec main does not match anyYour branch is called master, or you haven’t committed yet.git branch -M main, after at least one commit
You are in 'detached HEAD' stateYou checked out a commit, not a branch.git switch -c new-branch to keep any work, or git switch main
Please commit your changes or stash them before you switch branchesUncommitted edits would be overwritten.git stash, switch, then git stash pop
CONFLICT (content): Merge conflict in fileTwo branches changed the same lines.See resolving a merge conflict
fatal: Need to specify how to reconcile divergent branchesBoth you and the remote have new commits, and Git doesn’t know whether to merge or rebase.git config –global pull.rebase false once, then git pull
Permission denied (publickey)The server doesn’t recognise your SSH key.Add your .pub key to your account; test with ssh -T git@github.com
fatal: not a git repository (or any of the parent directories)You are not inside a repository folder.cd into the project, or git init
warning: in the working copy of 'file', LF will be replaced by CRLF the next time Git touches itGit is converting line endings for Windows.Usually harmless; add a .gitattributes file to make it consistent
fatal: The current branch feature/x has no upstream branchGit doesn’t know where to push a branch it hasn’t pushed before.git push -u origin feature/x (once; plain git push works after that)
error: Your local changes to the following files would be overwritten by mergegit pull would overwrite edits you haven’t committed.Commit them, or git stash, git pull, then git stash pop

The most common Git mistakes, and how to fix them

Nearly everyone makes these, usually in their first year. Each has a fix, and most are prevented by a habit or a setting.

MistakeWhy it hurtsThe fix
Committing a password, API (application programming interface) key or .env fileAnyone with the repository has it, in every copy, forever.Revoke the secret at once, then remove it from history (git filter-repo, a separate install) if needed. Add .env to .gitignore and turn on your host’s secret scanning.
Committing straight to mainUnreviewed changes reach everyone, and main may stop working.Protect main so changes arrive by pull request. If you have not pushed: git switch -c my-work, then git branch -f main origin/main.
Force-pushing a shared branchIt rewrites history under your colleagues’ feet and can delete their work.Use git push –force-with-lease, and only on your own branches. Never on main.
Rebasing commits others already haveTheir copies no longer match; merging them creates duplicates.Rebase only local or personal branches. Merge or revert on shared ones.
Starting work without pulling firstYou build on an old version and meet conflicts later.git pull (or git fetch and look) before you start, and keep branches short.
One giant commit at the end of the weekImpossible to review, hard to revert, useless in history.Commit each logical step. git add -p stages part of a file.
Messages like ‘fix’ or ‘updates’Six months later nobody knows what changed or why.A short summary in the imperative mood, plus why if it isn’t obvious. Consider Conventional Commits.
git add . with no .gitignoreBuild files, logs and node_modules end up in history.Create a .gitignore first; github.com/github/gitignore has templates for most languages.
git reset –hard with uncommitted workUncommitted edits are deleted with no way back.Run git status first. git stash is the safe way to clear your working tree.
Panicking in a merge conflictHalf-resolved files with <<<<<<< markers get committed.Read the markers, choose, test, then git add and git commit. git merge –abort starts again.
Long-lived feature branchesThe longer a branch lives, the worse the merge.Merge to main every day or two; hide unfinished features behind a feature flag.
Large binary files in historyClones become slow and huge, permanently.Use Git LFS (Large File Storage) for videos, design files and datasets, or keep them out of Git.
Mixed line endingsEvery line shows as changed when Windows and Mac users share files.Commit a .gitattributes file containing * text=auto, then run git add –renormalize . once and commit. It applies to everyone, unlike core.autocrlf (which Git for Windows already sets).
Renaming a file by changing its case onlyMac and Windows ignore the change, so Git never sees it.git mv readme.md README.md
Committing in detached HEADThose commits belong to no branch and are easily lost.git switch -c new-branch before you leave, or find them later in git reflog.
Forgetting what you stashedStashes pile up and get dropped by accident.Name them (git stash push -m) and clear them out with git stash list.

Git commands: the full reference

The Git commands worth knowing, grouped by what you are trying to do. Each has an example you can copy. git switch and git restore replaced the older, overloaded git checkout for most jobs in Git 2.23 (2019); you’ll still see checkout in older guides, and it still works.

git config: set up and configure

CommandWhat it doesExampleNote
git config --global user.nameSet the name recorded on your commitsgit config --global user.name "Priya Shah"
git config --global user.emailSet the email recorded on your commitsgit config --global user.email "priya@example.co.uk"Use the address your hosting service knows
git config --global init.defaultBranchName the first branch of new repositoriesgit config --global init.defaultBranch mainGit 2.28 or later
git config --global pull.rebaseChoose what git pull does when branches have divergedgit config --global pull.rebase falsefalse merges; true rebases
git config --list --show-originShow every setting and the file it came fromgit config --list --show-origin
git helpOpen the manual for any commandgit help rebasegit rebase -h for a short summary

Start a project

CommandWhat it doesExampleNote
git initTurn the current folder into a repositorygit initCreates a hidden .git folder
git cloneCopy a repository, its branches and its historygit clone git@github.com:acme/website.gitAdd a folder name to choose where it goes
git remote -vList the remote repositories this one talks togit remote -v
git remote addConnect a remotegit remote add origin git@github.com:priya/website.git

Everyday changes

CommandWhat it doesExampleNote
git statusShow changed, staged and untracked filesgit status -s-s for the short format
git addStage changes for the next commitgit add src/login.jsgit add -p lets you pick parts of a file
git commitSave the staged changes with a messagegit commit -m "Fix login timeout on slow connections"Leave out -m to write a longer message in your editor
git commit -aStage every tracked file and commit in one stepgit commit -am "Update copyright year"New files still need git add
git diffShow changes not yet stagedgit diffgit diff –staged shows what will be committed
git rmDelete a file and stage the deletiongit rm old-notes.txt–cached stops tracking but keeps the file; -r for a folder
git mvRename or move a file and stage itgit mv Readme.md README.mdThe safe way to change a name’s case on Mac and Windows

Branches

CommandWhat it doesExampleNote
git branchList local branches; -a includes remote onesgit branch -a
git switch -cCreate a branch and move to itgit switch -c feature/invoice-pdfOlder equivalent: git checkout -b
git switchMove to an existing branchgit switch mainCommit or stash your changes first
git branch -mRename a branchgit branch -m old-name new-nameOn the current branch: git branch -m new-name
git branch -dDelete a branch that has been mergedgit branch -d feature/invoice-pdf-D forces it, even if unmerged
git push origin --deleteDelete a branch on the remotegit push origin --delete feature/invoice-pdf
git mergeBring another branch’s commits into this onegit merge feature/invoice-pdf–no-ff always records a merge commit
git rebaseReplay your commits on top of another branchgit rebase mainOnly on branches nobody else uses

How to rename or delete a Git branch, locally and on the remote

Renaming or deleting a branch that is already on the remote takes two steps: change it locally, then update the remote. To rename: git branch -m old-name new-name, git push -u origin new-name, then git push origin --delete old-name. To delete: git branch -d name and git push origin --delete name. Colleagues’ copies keep the old name as origin/old-name until they run git fetch --prune.

Sharing with others

CommandWhat it doesExampleNote
git fetchDownload others’ commits without changing your workgit fetch originSafe at any time
git pullFetch, then merge (or rebase) into your branchgit pullgit fetch followed by git merge
git pushSend your commits to the remotegit pushFirst time on a branch: git push -u origin feature/x
git push --force-with-leaseOverwrite a remote branch, but only if nobody else has pushed to itgit push --force-with-leaseNever plain –force on a shared branch. Editors that fetch in the background (VS Code does) can let the lease pass anyway; add –force-if-includes (Git 2.30+) for full protection.

History and investigation

CommandWhat it doesExampleNote
git logShow commit historygit log --oneline --graph --all-p shows each commit’s changes
git showShow one commit in fullgit show a1b2c3d
git blameShow who last changed each line, and whengit blame -L 40,60 src/login.jsFor context, not for blame
git log -SFind the commits that added or removed some textgit log -S "TIMEOUT_MS" --oneline
git bisectBinary-search history for the commit that broke somethinggit bisect start; git bisect bad; git bisect good v1.4.0Then mark each step good or bad; git bisect reset when you have finished
git reflogEvery position HEAD has been in: the safety netgit reflogRecover ‘lost’ commits from here

Undo and fix

CommandWhat it doesExampleNote
git restoreDiscard unstaged edits to a filegit restore src/login.jsCannot be undone
git restore --stagedUnstage a file but keep the editsgit restore --staged src/login.js
git commit --amendChange the last commit’s message or add a forgotten filegit commit --amendNot yet pushed only
git reset --softUndo commits but keep their changes stagedgit reset --soft HEAD~1Not yet pushed only
git reset --hardThrow away commits and all uncommitted editsgit reset --hard HEAD~1Destructive
git revertAdd a new commit that reverses an earlier onegit revert a1b2c3dThe safe undo for shared history
git cleanDelete untracked filesgit clean -n-n previews; -f actually deletes

git stash, cherry-pick and tag

CommandWhat it doesExampleNote
git stashPut uncommitted changes asidegit stash push -m "half-done invoice layout"-u includes untracked files
git stash listSee what is stashedgit stash list
git stash popBring the latest stash back and remove it from the listgit stash popgit stash apply keeps it in the list
git cherry-pickCopy one commit onto the current branchgit cherry-pick a1b2c3dIdeal for back-porting a hotfix
git tagMark a commit, usually a releasegit tag -a v2.4.0 -m "Release 2.4.0"Push it with git push origin v2.4.0

Power moves

Once the basics are second nature, these save real time. Interactive rebase is how you squash or tidy commits before a pull request; do it only on commits you haven’t pushed.

CommandWhat it doesExampleNote
git rebase -iSquash, reword or reorder your recent commitsgit rebase -i HEAD~3Not yet pushed only; change pick to squash or fixup
git commit --fixupRecord a fix to an earlier commit, to be folded in latergit commit --fixup a1b2c3dThen git rebase -i –autosquash main
git switch -Jump back to the branch you were on beforegit switch -
git pull --rebaseReplay your local commits on top of others’ instead of merginggit pull --rebaseKeeps history straight on your own branch
git worktree addCheck out a second branch in another folder, at the same timegit worktree add -b hotfix/PAY-160 ../hotfix origin/mainStart a hotfix in another folder without stashing
git config aliasMake your own short commandsgit config --global alias.lg "log --oneline --graph --all"Then git lg
git remote set-urlChange where a remote points, for example from an https:// address to SSHgit remote set-url origin git@github.com:priya/website.git
git log --author --sinceFilter history by person and dategit log --author="Priya" --since="2 weeks ago" --oneline

git checkout vs git switch and git restore

git checkout used to do two unrelated jobs: moving between branches and throwing away changes to files. Git 2.23 split them into git switch and git restore, which are harder to misuse. Both versions work:

Older commandNewer commandWhat it does
git checkout branchgit switch branchMove to a branch
git checkout -b newgit switch -c newCreate a branch and move to it
git checkout -- filegit restore fileDiscard unstaged edits
git reset HEAD filegit restore --staged fileUnstage a file
git checkout a1b2c3dgit switch --detach a1b2c3dLook at an old commit (detached HEAD)

Git merge vs rebase, and how to resolve merge conflicts

Merge and rebase both bring two lines of work together; the difference is what the history looks like afterwards and whether commits are rewritten. The safe rule: merge into shared branches, rebase only your own.

git mergegit rebase
What it doesJoins two branches with a merge commitReplays your commits on top of the other branch
HistoryShows exactly what happened, including the branchingA straight line, as if the work happened in order
Commit IDsUnchangedRewritten (new hashes)
Safe on shared branches?YesNo: only on branches nobody else uses
ConflictsResolved once, in the mergeMay need resolving once per replayed commit
Use it whenBringing finished work into mainTidying your own branch before a pull request

Squash merging turns all the commits on a pull request into one when it is merged, which keeps main’s history tidy. The catch: Git no longer sees the original branch as merged, so delete it with git branch -D.

How to resolve a merge conflict

A merge conflict means two branches changed the same lines in different ways, and Git needs a person to decide. It is routine, not an error. Git marks the clash in the file like this:

<<<<<<< HEAD
const TIMEOUT_MS = 30000;
=======
const TIMEOUT_MS = 45000;
>>>>>>> feature/slow-networks
  1. Run git status to see which files conflict.
  2. Open each file. Between <<<<<<< HEAD and ======= is your branch’s version; between ======= and >>>>>>> is the incoming one. During a rebase the sides are reversed: HEAD is the branch you are rebasing onto.
  3. Edit the file to the correct result, which may be one side, the other, or a mix, and delete all three marker lines.
  4. Test it, then git add the file. When every file is resolved, git commit (or git rebase --continue during a rebase).
  5. Lost? git merge --abort puts everything back as it was before the merge (git rebase --abort during a rebase).

Writing good commit messages (and Conventional Commits)

A good commit message has a short summary line in the imperative mood, such as “Fix login timeout on slow connections”, then a blank line and a few lines on why, if it isn’t obvious. Keep the summary under about 72 characters so it reads well in git log --oneline and on GitHub.

Conventional Commits is a widely used convention that adds a type to the start of the summary. It makes history scannable and lets tools generate release notes and version numbers automatically. A ! after the type, or a BREAKING CHANGE: footer, marks a change that breaks compatibility.

TypeUse it forExample
featA new featurefeat(invoices): add PDF download
fixA bug fixfix(login): retry once on network timeout
docsDocumentation onlydocs: explain the release process
refactorCode change that neither fixes nor addsrefactor: split payment service
testAdding or fixing teststest: cover refunds of zero-value lines
choreHousekeeping: builds, dependencieschore: update dependencies

Git branching strategies: which one fits your team?

A branching strategy is the team’s agreement on which branches exist, how long they live and how work reaches production. The right one depends mostly on how often you release. The shortest summary: release continuously and keep branches short-lived (trunk-based development or GitHub flow); release on a schedule and add release branches; support several versions at once and consider GitFlow; accept work from strangers and use forks.

StrategyHow it worksBest forWatch out
Trunk-based developmentEveryone commits to main, or to branches merged within a day or two at mostTeams with good automated tests that deploy oftenNeeds feature flags and discipline
GitHub flowShort feature branch, pull request, merge to main, deploy mainSolo developers and small teams shipping continuouslyNo place for a release in testing
Release branchesMain plus a branch per release; fixes go to main first, then are cherry-picked to the releaseTeams on a fixed release rhythm, such as weeklyEvery fix needs a second pull request
GitFlowdevelop, main, feature, release and hotfix branchesProducts with versioned releases supported side by sideHeavy for teams that deploy often
Forking workflowContributors work in their own copy and send pull requestsOpen-source projects and outside contributorsContributors must keep forks up to date

GitFlow, described by Vincent Driessen in 2010, was the default for years. In 2020 he added a note to the original article recommending simpler workflows such as GitHub flow for software that is delivered continuously, and keeping GitFlow for explicitly versioned software. Atlassian now describes it as a legacy workflow, and the DORA (DevOps Research and Assessment) studies link short-lived branches merged at least daily with better delivery performance. GitFlow is still worth knowing, because many established codebases use it.

These recommendations follow published practice: Microsoft’s Release Flow, trunkbaseddevelopment.com, Martin Fowler’s branching patterns, the DORA research, and GitHub’s own guidance on GitHub flow and contributing to projects.

Trunk-based development vs GitHub flow vs GitFlow

Trunk-based development means everyone integrates into one branch, main (the “trunk”), at least daily, using branches that live hours or a day or two rather than weeks, and feature flags to hide unfinished work. GitHub flow is the same idea with a pull request on every change. GitFlow adds long-lived develop, release and hotfix branches, and suits software that ships numbered versions supported side by side.

Four questions settle most choices:

If the answer is yes to…Use
Do you deploy every time something merges?Trunk-based development or GitHub flow
Do you release on a schedule, such as weekly?Add a release branch per release (as in the team example below)
Do customers run several versions that you patch?GitFlow, or long-lived release branches per version
Do strangers contribute?Forking workflow with pull requests

A solo developer: main plus short branches

Working alone, keep it simple: main is the version that works. Use a short branch for anything that takes more than one sitting or might not work out; a small, tested fix can go straight onto main. Either way, run your tests before main moves on. Push to a hosting service even if nobody else will see it: it is also your off-site backup.

  1. Start anything bigger than a quick fix on a short branch
    git switch -c fix/vat-rounding
  2. Commit as you go, in small steps
    git commit -am "Round VAT per line, not per invoice"
  3. Merge back when it works, then delete the branch
    git switch main
    git merge fix/vat-rounding
    git branch -d fix/vat-rounding
  4. Tag what you release, so you can always get back to it
    git tag -a v1.3.0 -m "Release 1.3.0"
    git push origin main v1.3.0

A team of ten: weekly sprints, weekly releases and hotfixes

For a team of around ten working in weekly sprints, releasing to production every week and occasionally needing an urgent fix, use short-lived feature branches into main plus a release branch per week. This is trunk-based development with release branches, the pattern Microsoft calls Release Flow. Release branches are never merged back into main. Every fix is made on main first and then cherry-picked into the release branch (“upstream first”), so a fix can’t be forgotten in next week’s release.

  • main is always releasable. Nobody commits to it directly: protect it in GitHub, GitLab or Azure DevOps so every change arrives by pull request with at least one approval, passing status checks and force pushes blocked. A CODEOWNERS file can require review from the people who own the code being changed.
  • One branch per ticket, merged within a day or two. Name it after the ticket: feature/PAY-142-card-refunds. Small branches mean small reviews and few conflicts.
  • Cut a release branch on a fixed day. On Thursday morning, release/2026-45 (the year and week number) is created from main, deployed to staging, tested and released to production that afternoon. main carries straight on with next week’s work.
  • Tag every production release. v2026.45.0 marks exactly what went live, so anyone can rebuild it.
  • Tidy up after each release. Only the release manager creates release/* branches. Once the next week’s release is live, delete the old release branch; its tag keeps the code.
  • Hotfixes go to main first, then to the release. Fix the bug on a branch from main, merge it, then cherry-pick that one commit into the live release branch through a second pull request. Only the fix travels, not next week’s untested work. The exception: if the bug no longer exists on main, or main has changed so much that the fix doesn’t apply, fix the release branch directly and record on the ticket why main needs no change, or make the matching fix on main the same day.

If a bug is found in production the following Monday, the fix is merged into main and cherry-picked into release/2026-45, which is released as v2026.45.1 on Tuesday. Thursday’s release/2026-46 is cut from main, so it already has the fix.

Weekly release and upstream-first hotfixFeature branches merge into main through pull requests. On Thursday a release branch is cut from main, tagged v2026.45.0 and deployed. The following week a fix is made on a branch from main and merged into main, then cherry-picked into the release branch, tagged v2026.45.1 and deployed.Weekly releases with an upstream-first hotfixMonTueWedThuFriMonTueWedWeek 45Week 46feature/*hotfix/*mainrelease/2026-45pull requests into mainThursday: cut releasev2026.45.0deploy1 fix on main firstv2026.45.12 cherry-pick torelease (via pull request)
Feature branches flow into main; each week’s release gets its own branch; a hotfix lands on main first and is cherry-picked into the release.

The hotfix, step by step. Cherry-pick the fix commit, not the pull request’s merge commit; if the pull request was squash-merged, use the squash commit. Azure DevOps and GitLab have a cherry-pick button on the merged pull request that does step 3 and opens the pull request in step 4 for you.

  1. Branch from main and reproduce the bug with a failing test
    git fetch origin
    git switch -c hotfix/PAY-160-refund-crash origin/main
  2. Fix, commit, push and open a pull request into main
    git commit -am "Fix crash when refunding a zero-value line"
    git push -u origin hotfix/PAY-160-refund-crash
  3. After review and passing checks, merge it, then cherry-pick the fix onto a branch from the live release
    git fetch origin
    git log --oneline -5 origin/main
    git switch -c hotfix/PAY-160-to-2026-45 origin/release/2026-45
    git cherry-pick -x <fix-commit-hash>
    git push -u origin hotfix/PAY-160-to-2026-45
  4. Open a pull request into release/2026-45 (change the base branch: it defaults to main). After review, merge, tag and deploy
    git switch release/2026-45
    git pull
    git tag -a v2026.45.1 -m "Hotfix PAY-160"
    git push origin v2026.45.1

Would GitFlow work for this team? It would, but its long-lived develop branch and separate release and hotfix merges add ceremony that a team deploying weekly rarely needs. Choose it if you must keep, say, versions 3 and 4 of a product supported side by side for different customers.

Open source: how to fork a repository and make your first contribution

Open-source projects use a forking workflow: you can’t push to their repository, so you work in your own copy and send them a pull request. It is how most people contribute to projects whose maintainers they have never met, and a good first contribution (a documentation fix, a test, a small bug fix) is the best way to learn it.

Forking workflow diagram1: fork the original project to your own account. 2: clone your fork to your computer. 3: push your branch to your fork. 4: open a pull request from your fork to the original project. 5: fetch from upstream to keep your copy current.Contributing to an open-source projectOriginal projectupstream · github.com/org/projectYour forkorigin · github.com/priya/projectYour computeryour clone, where you work1 Fork4 Pull request2 git clone3 git push5 git fetch upstream
You can’t push to the original project, so you push to your fork and ask the maintainers to pull from it.
  1. Read the rules first

    Look for CONTRIBUTING.md, the code of conduct and issues labelled ‘good first issue’, and search open and closed issues in case it has been discussed. For anything bigger than a typo, comment on the issue before you start, so nobody duplicates your work.

  2. Fork the project

    On GitHub, press Fork. You now have your own copy, at github.com/priya/project, that you can push to.

  3. Clone your fork and add the original as ‘upstream’
    git clone git@github.com:priya/project.git
    cd project
    git remote add upstream https://github.com/original-org/project.git
  4. Branch from the latest upstream main (never work on your fork’s main, which you keep as a clean copy of upstream)
    git fetch upstream
    git switch -c fix/typo-in-install-guide upstream/main
  5. Make the change, following the project’s style and tests
    git add docs/install.md
    git commit -s -m "docs: fix typo in install guide"
  6. Push to your fork and open a pull request: say what it changes and why, add ‘Closes #123’ and tick Allow edits from maintainers
    git push -u origin fix/typo-in-install-guide
  7. Respond to review by pushing more commits to the same branch
    git commit -am "docs: reword per review"
    git push
  8. Keep your fork current for next time (or press Sync fork on GitHub)
    git switch main
    git fetch upstream
    git merge --ff-only upstream/main
    git push
  • Many projects require a sign-off or an agreement. git commit -s adds the Signed-off-by line, with your real name and email, used by the Linux kernel and others under the DCO (Developer Certificate of Origin); some projects ask you to sign a CLA (Contributor Licence Agreement) instead. -s is a statement that you have the right to submit the work, not a cryptographic signature (that is -S).
  • One change per pull request. A focused pull request (PR) with a clear description gets reviewed; a sprawling one waits.
  • Be patient and polite. Maintainers are often volunteers. If a week passes without a reply, a friendly comment in the same thread is fine; don’t chase them privately.
  • Run the tests before you push. CI (continuous integration) will run them anyway, and a red build is the quickest way to be ignored.

Using Git in Visual Studio Code

Visual Studio Code has Git built in: open a folder that is a repository and the Source Control view shows every change, ready to stage, commit, push and pull without typing a command. It uses the Git installed on your computer, so install Git first. The terminal is still there (Ctrl+` opens it) when you need a command the buttons don’t offer.

ToIn VS Code
Open Source ControlCtrl+Shift+G (Control+Shift+G on a Mac too) shows every changed file.
See a changeClick a file to open a side-by-side diff of what you changed.
StageHover over a file and click +; or stage selected lines from the diff.
CommitType a message in the box at the top and press Commit (Ctrl+Enter, or Cmd+Enter on a Mac).
Push and pullSync Changes pushes and pulls in one go; the … menu has each separately.
Switch or create a branchClick the branch name in the bottom-left status bar.
Resolve a conflictConflicted files open with Accept Current, Accept Incoming and Accept Both above each clash, or in the three-way merge editor.
See historyThe Source Control Graph shows branches and commits; the Timeline view shows one file’s history.

To make VS Code the editor Git opens for commit messages and rebases, run git config --global core.editor "code --wait" (on a Mac, first run Shell Command: Install ‘code’ command in PATH from the Command Palette). GitHub Copilot, if you use it, adds a button in the commit message box that drafts a message from your changes; read it before you commit.

Three extensions worth knowing
ExtensionWhat it adds
GitHub Pull RequestsReview, comment on and merge pull requests without leaving the editor (GitLab Workflow does the same for GitLab).
GitLensInline blame, rich history and comparisons; the free tier covers most needs.
Code for IBM iEdit IBM i source in VS Code; source kept as stream files in the IFS (Integrated File System) can be managed with Git.

Using Git with Claude, ChatGPT and other AI assistants

AI assistants such as Claude, ChatGPT and GitHub Copilot are useful with Git: they explain commands, decode error messages, draft commit messages and help untangle conflicts. They are also confidently wrong sometimes, and Git has commands that destroy work. Use them as a knowledgeable colleague whose advice you check, not as an operator with your keys.

DoHow
Ask it to explain before you runPaste a command you found and ask what it does, what it changes and how to undo it.
Paste the error and git status, not your secretsThe exact message plus git status output gives it enough to diagnose most problems. Remove passwords, keys and customer data first.
Ask for the safest optionAdd ‘my branch is shared with others’ or ‘nothing is pushed yet’ to your question; the right answer often depends on it.
Draft commit messages from the diffGive it git diff --staged and ask for a Conventional Commits message. Read it before you commit: it can only describe what it sees, not why.
Untangle a conflictPaste the conflicted block and say what each side was meant to do. Check the result runs.
Review a pull requestAsk what could break, what is untested and what a reviewer would question. Treat it as a second reviewer, not the only one.
Generate a .gitignore or a hookIt is good at boilerplate for a given language or framework.

And don’t

  • Don’t run a destructive command (reset --hard, push --force, clean -f, filter-repo) because an assistant suggested it. Check the reflog and your remote first.
  • Don’t paste secrets, customer data or code you are not allowed to share. Check your organisation’s rules on which AI services may see its code.
  • Don’t trust invented flags. Assistants sometimes produce options that don’t exist; git help <command> settles it.
  • Don’t let an AI agent push to main. Agents that can run Git themselves, such as Claude Code, GitHub Copilot’s agent mode and OpenAI’s Codex, should work on their own branch and open a pull request that a person reviews.

Prompts that work well. Give the context the right answer depends on:

Explain safely

I'm on a feature branch that I've already pushed and a colleague has pulled. I want to undo my last two commits. What's the safest way, and what will it do to my colleague's copy?

Commit message

Here is my staged diff. Write a Conventional Commits message: a summary line under 72 characters and a short body explaining why. Don't invent reasons that aren't in the diff.

Rescue

Here is my git reflog. I think I lost a commit called 'Add refund export' after a reset. Which entry is it, and how do I get it back on a new branch?

Agents that run Git for you. Coding agents can now edit files, run tests and make commits on their own. Set them up the way you would a new starter: their own branch, no permission to push to main or force-push, and every change arriving as a pull request a person reviews. Start one on a new branch from a clean commit, so git diff main shows exactly what it changed and deleting the branch undoes it.

Git terms explained

Git has its own vocabulary, and most confusion comes from it. These are the terms you’ll meet in commands, error messages and code reviews, in plain English.

TermWhat it means
Repository (repo)A project folder that Git tracks, with its entire history stored in a hidden .git folder.
Working treeThe files you can see and edit: your current version of the project.
Staging area (index)The list of changes that will go into the next commit. git add puts changes here.
CommitA saved snapshot of the staged changes, with a message, an author, a date and a link to the commit before it.
Hash (SHA, Secure Hash Algorithm)The unique ID of a commit, such as a1b2c3d (the short form of a 40-character code). Git calculates it from the commit’s contents, so any change gives a new ID. Git uses SHA-1 by default; SHA-256 is available and planned to become the default in Git 3.0.
HEADGit’s pointer to where you are now: usually the latest commit on the branch you have checked out.
Detached HEADYou are looking at a specific commit rather than a branch. New commits here are easy to lose; create a branch (git switch -c) to keep them.
BranchA movable label pointing at a commit, used for a separate line of work. Creating one is instant.
main (formerly master)The usual name of the primary branch. GitHub switched its default from master to main in October 2020.
TagA fixed label on a commit, usually marking a release. Annotated tags (-a) also store a message and author.
RemoteAnother copy of the repository that you push to and pull from, usually on a hosting service.
originThe default name Git gives the remote you cloned from.
upstreamThree meanings: the original project your fork came from; the remote branch your local branch tracks; and, in ‘upstream first’, main as opposed to a release branch.
CloneA full copy of a repository, history included, made with git clone.
ForkYour own server-side copy of someone else’s repository, so you can push changes without write access to theirs. A hosting feature, not a Git command.
FetchDownload new commits from a remote without changing your files.
PullFetch, then merge (or rebase) the new commits into your branch.
PushUpload your commits to a remote branch.
MergeCombine another branch’s work into the current branch.
Fast-forwardA merge where your branch has no new commits of its own, so Git moves the label forward with no merge commit.
Merge commitA commit with two parents, recording where two branches joined.
RebaseReplay your commits on top of another branch, giving a straight-line history. It rewrites commit IDs, so don’t rebase shared branches.
SquashCombine several commits into one, often when a pull request is merged.
Cherry-pickCopy a single commit from one branch to another.
StashA shelf for uncommitted changes, so you can switch branch and come back to them.
ConflictTwo branches changed the same lines differently. Git marks the clash and asks you to choose.
DiffThe line-by-line difference between two versions.
ReflogGit’s private record of everywhere HEAD has been: kept for 90 days by default, and 30 days for commits no branch points to. The way back after most mistakes.
.gitignoreA file listing what Git should never track: build output, logs, .env files, node_modules.
Pull request (PR)A request to merge one branch into another, with a page for reviewing, discussing and testing the change first. See below for why it is called a pull.
Merge request (MR)GitLab’s name for a pull request. It does exactly the same job.
Code reviewColleagues reading a pull request’s changes and approving them or asking for changes.
CI (continuous integration)Automated builds and tests that run on every push or pull request.
Protected branchA branch, usually main, that can only change through approved pull requests.
Git LFS (Large File Storage)An extension that keeps large files such as videos and design files outside the normal history.
HookA script Git runs automatically at a point such as before a commit, for example to run tests or a formatter.
SubmoduleA repository nested inside another at a fixed commit. Powerful, and easy to get wrong.
TrunkAnother name for main: the branch everyone integrates into.
Feature flagA setting that hides unfinished code in production, so it can be merged before it is ready.

What is a pull request, and why is it called that?

A pull request asks the maintainers of a repository to merge your branch, with a page for review, discussion and automated checks before it lands. It is called a pull request because in Git you cannot push into someone else’s repository; they have to pull your changes into theirs. Since July 2005 Git has had a git request-pull command, which writes a summary email asking a maintainer to pull from your copy: that is how Linux kernel maintainers still send their work up to Linus Torvalds. In February 2008 GitHub added a Pull Request button that sent the request as a message; by 2010 it had become a web page with the changes and a discussion, and reviews and automated checks followed. GitHub kept the name. GitLab, launched in 2011, chose “merge request”, describing what happens rather than who does it. They are the same thing.

How Git differs from SVN and earlier version control

The big difference: Subversion (SVN) is centralised, with one server holding the history, while Git is distributed, so every copy is a complete repository. With SVN you check out a working copy and every commit goes straight to the server. With Git you commit locally, as often as you like, and push to a shared repository when you are ready. That one design choice is why Git branches are cheap, why it is fast, and why you can work on a train.

Centralised vs distributed version controlIn Subversion, working copies hold only the latest files and talk to one server that holds all history. In Git, every developer has a full repository with all history and pushes to and pulls from a shared repository.Centralised (SVN) vs distributed (Git)Subversion: one server holds the historySVN serverall historyWorking copylatest files onlyWorking copylatest files onlyWorking copylatest files onlyEvery commit and most commands need the serverGit: every copy is a full repositoryShared repositoryGitHub, GitLab, Azure DevOpsFull repositoryall history, offlineFull repositoryall history, offlineFull repositoryall history, offlineCommit locally; push and pull when you choose
With Subversion every commit goes to the server; with Git every developer has the whole history.
Fifty years of version control in five steps
YearSystem
1972SCCS (Source Code Control System) at Bell Labs: one file at a time
1982RCS (Revision Control System): still one file at a time, on one machine
1990CVS (Concurrent Versions System): many files, a central server
2000Subversion (SVN): a better CVS, with atomic commits
2005Git and Mercurial: distributed, every copy is a full repository

Git vs SVN at a glance

GitSubversion (SVN)
ModelDistributed: every clone has the full historyCentralised: one server holds the history
Work offlineCommit, branch, diff and view history with no networkCommit, log, branch and update need the server; status and diff work offline
CommittingCommit locally, then push when readyEvery commit goes straight to the server
BranchesCheap pointers; created and merged in secondsCopies of directories; merging has historically been harder
Version IDsA hash such as a1b2c3dA rising number: r1, r2, r3
Partial checkoutWhole repository (sparse checkout is possible)Any sub-folder on its own
Large binary filesAwkward; Git LFS (Large File Storage) helps, and adds file lockingHandled well, with file locking
Access controlPer repository, set by the hosting serviceCan be set per folder
SpeedMost commands are local, so fastDepends on the network and server

SVN still has its place. Teams with very large binary files that must be locked while someone edits them, with huge repositories where people only need one folder, or that need permissions set per folder, sometimes stay with SVN, or with Perforce in games studios. For almost everything else, Git has won.

SVN commands and their Git equivalents

SVNGitNote
svn checkout URLgit clone URLGit copies the whole history, not just the latest files
svn updategit pull
svn commitgit commit, then git pushTwo steps: save locally, then share
svn add / svn deletegit add / git rm
svn loggit log
svn revert filegit restore file
svn copy trunk branches/xgit switch -c xA Git branch is a label, not a copy
svn mergegit merge

Moving from SVN? git svn can bridge the two while you migrate, and the main hosting services import SVN repositories with their history. Think of trunk as main, and of each SVN branches/ folder as a Git branch.

Download the Ultimate Git Cheat Sheet

Cover of the Ultimate Git Cheat Sheet A5 mini-ebook

Keep it beside the keyboard

The same guide as a printable A5 booklet, with a pin-up survival card on the back.

Download the PDF (36 pages, free, no sign-up)

Edition 1 · November 2026 · CC BY-NC-ND 4.0 · Print at A5 or two to an A4 sheet.

Know someone learning Git? Share it:LinkedInFacebookXWhatsAppEmail

Git questions answered

What is Git in simple terms?

Git is version control: it records every saved change to a set of files, who made it and why, so you can see history, undo mistakes and work alongside other people without overwriting each other. It runs on your own computer and is free and open source.

What is the difference between Git and GitHub?

Git is the version control tool that runs on your computer. GitHub is a website that hosts Git repositories and adds pull requests, issue tracking, automation and access control. GitLab, Bitbucket and Azure DevOps do the same job as GitHub.

How do I undo the last commit in Git?

If you haven’t pushed it, git reset –soft HEAD~1 removes the commit and keeps your changes staged. If you have pushed it, use git revert followed by the commit’s hash, which adds a new commit that reverses it without rewriting shared history.

What is the difference between git fetch and git pull?

git fetch downloads new commits from the remote but leaves your files and branches alone, so you can look first. git pull does a fetch and then merges (or rebases) those commits into your current branch.

Should I use merge or rebase?

Merge to bring finished work into a shared branch such as main; it keeps the real history and never rewrites commits. Rebase to tidy your own unpublished branch before opening a pull request. Never rebase commits other people already have.

What is trunk-based development?

A branching strategy in which everyone merges small changes into main at least once a day, instead of keeping long-lived feature branches. Unfinished work is hidden behind feature flags, and automated tests keep main releasable at all times.

What does git stash do?

git stash puts your uncommitted changes on a shelf and returns your files to the last commit, so you can switch branch. git stash pop brings the changes back; git stash list shows what is stored.

How do I squash commits in Git?

To combine your last three unpushed commits, run git rebase -i HEAD~3 and change pick to squash on the second and third lines. Alternatively, git reset –soft HEAD~3 followed by one git commit does the same. Don’t squash commits others already have.

Which Git branching strategy should I use?

A solo developer or a small team deploying often does well with GitHub flow or trunk-based development: short branches, pull requests and an always-releasable main. A team on a fixed weekly release adds a release branch per week; fixes go to main first and are cherry-picked into the release. GitFlow suits products that support several released versions at once. Open-source projects use forks.

How do I rename a Git branch?

git branch -m new-name renames the branch you are on; git branch -m old-name new-name renames another. If it was already pushed, push the new name with git push -u origin new-name and delete the old one with git push origin –delete old-name.

How do I delete a Git branch?

git branch -d name deletes a local branch that has been merged; -D forces it. To delete it on the remote, use git push origin –delete name.

What is the difference between git checkout, git switch and git restore?

git checkout used to switch branches and also discard changes to files, which made it easy to lose work by accident. Since Git 2.23 (2019), git switch moves between branches and git restore discards or unstages changes. git checkout still works, but the newer commands are clearer and safer.

What is HEAD in Git?

HEAD is Git’s pointer to where you are now: normally the latest commit on your current branch. A detached HEAD means you have checked out a specific commit rather than a branch; any commits you make there belong to no branch, so create one with git switch -c before moving away.

Why is the main branch called main and not master?

Git 2.28 (July 2020) added a setting for the default branch name. GitHub changed its default for new repositories from master to main in October 2020, and GitLab and Bitbucket followed in 2021. Git itself plans to make main the default in Git 3.0. Older repositories may still use master; both work the same way.

Is there a free Git cheat sheet PDF?

Yes. The A5 Ultimate Git Cheat Sheet on this page is free to download with no sign-up, and free to share for non-commercial use under a Creative Commons licence. Its QR code brings you back here for the latest edition.

Further reading

Leave a Comment