Git Cheatsheet
The commands that earned their place. Companion reference for the Git for Network Engineers series.
The commands that earned their place. This page is the printable companion to the Git for Network Engineers series — the bit you keep open in another tab.
Hit Print / Save as PDF above to take it with you.
Setup
One-time global config on a new machine.
git config --global user.name "Your Name"Identity attached to every commit you make.git config --global user.email "[email protected]"Email tied to your GitHub account.git config --global init.defaultBranch mainStop the master/main warning on every new repo.git config --global pull.rebase trueDefault everygit pullto rebase. Cleaner history, no merge commits.ssh-keygen -t ed25519 -C "you@host"Generate an SSH key. Paste the .pub into GitHub → SSH Keys.gh auth loginAuthenticate the GitHub CLI. Web-browser flow is the easiest path.gh auth statusVerify you are logged in and which scopes the token has.
The daily loop
Branch, edit, commit, push, PR, merge, sync. Repeat.
git switch -c feature/short-descriptionCreate and switch to a new feature branch off the current one.git switch -Return to the previously checked-out branch. Thecd -for git.git statusWhat changed, what is staged, what is untracked. Run constantly.git add <file> / git add .Stage a specific file, or everything in the current dir and below.git add -pInteractive staging by hunk. Pick exactly which changes go in the commit.git commit -m "what this commit does"Take what is staged, save it as a snapshot with that message.git push -u origin <branch>First push of a branch. Sets it to track origin. After this, justgit push.gh pr create --fillOpen a PR.--fillauto-uses commit messages for title/body.gh pr merge --squash --delete-branchSquash-merge the PR, delete the branch locally and remotely.git switch main && git pullBack to main, sync with the merged result.
Inspect history
Reading the past. Use these before changing anything.
git log --oneline -10Last 10 commits, compact view. The defaultgit logis too noisy.git log --oneline --graph --allVisualize branches and merges across the whole repo.git log --grep="ci"Filter commits by message text (basic regex by default).git log --author="tonhe"Every commit by an author whose name or email matches.git log --since="2 weeks ago"Time-bounded log. Also--until=for a closing bound.git log -- path/to/file.ymlEvery commit that touched that file. Note the--.git log -p -- path/to/file.ymlSame as above, but with the full diff inline for each commit.git log --follow path/to/file.ymlTrack a file through renames. Useful when a file has moved.git show <sha>Full diff of a specific commit. Add--statfor just the file list.git show <sha>:path/to/fileRead the contents of a file as it was at that commit.git blame <file>Who wrote each line and when. The “why is it like this” command.git blame -L 11,12 <file>Blame only specific lines. Useful for long files.git diff / git diff --stagedUnstaged changes vs. staged changes. Run before every commit.
Power tools
History as an investigation instrument.
git cherry-pick <sha>Apply a single commit from another branch onto the current branch.git cherry-pick --abortBail out if a cherry-pick conflicts and you do not want to resolve.git bisect startBegin a binary search for the commit that broke something.git bisect bad HEAD / git bisect good <sha>Mark current state as broken and a known-good commit. Git checks out the midpoint.git bisect good / git bisect badAfter testing the midpoint, mark it. Git narrows the range.git bisect run <script>Automated bisect. Your script exits 0 for good, non-zero for bad.git bisect resetEnd the bisect session and return to your starting branch.git rebase -i HEAD~3Interactive rebase. Squash, reword, drop, reorder the last 3 commits.git rebase mainReplay the current branch on top of latest main. Clean linear history.
Recovery
When you mess up. `git reflog` is your time machine.
git reflogEvery place HEAD has been. Find the SHA of the thing you “lost,” recover from there.git commit --amend --no-editAdd staged changes to the previous commit. Local only, never amend pushed commits.git commit --amend -m "new message"Rewrite the most recent commit message. Still local only.git restore --staged <file>Unstage a file. Modern replacement forgit reset HEAD <file>.git restore <file>Discard unstaged edits. Destructive: gone for good.git revert <sha>New commit that undoes a published commit. Safe for shared history.git reset --soft HEAD~1Undo last commit, keep changes staged. Useful for restructuring.git reset --hard <sha>Move branch to that SHA, throw out everything past it. Dangerous on shared branches.git stash push -u -m "wip"Save uncommitted work (incl. untracked with -u) so you can switch branches.git stash list / git stash popSee the stack of stashes. Pop the most recent one off and reapply.git stash apply / git stash dropapplyreapplies but keeps the stash on the stack.dropdiscards without applying.git switch -c recover-it <sha>Bring a deleted branch back. Get the SHA fromgit reflog.git push --force-with-leaseForce-push, but only if nobody else pushed since you last fetched. Never use plain –force.git filter-repo --invert-paths --path <file> --forceRemove a file from all history. After a credential leak. Rotate the credential first.
Remotes and sync
Talking to the world beyond your laptop.
git remote -vList configured remotes and their URLs.originis the convention.git remote add origin <url>Connect a local repo to a remote. Done once per repo.git remote set-url origin <url>Change a remote URL. Use this to switch from HTTPS to SSH.git fetch --prunePull down remote refs and clean up references to branches deleted on the remote.git pull --rebaseFetch + rebase your local commits on top. Cleaner than the default fetch+merge.git branch -aList all branches, local and remote-tracking.git branch --show-currentJust the current branch name. Scriptable. Useful for shell prompts and CI.git branch -d <name> / git branch -D <name>Delete a merged branch. Capital-Dforces deletion of unmerged branches.git branch -m old-name new-nameRename a local branch. Oftengit branch -m mainto rename from master.
Releases and tags
Annotated tags are how you mark known-good points. `git push --tags` ships them.
git tagList all tags in the repo.git tag -a v1.0 -m "release notes"Create an annotated tag at HEAD.-amakes it a real object with author and message.git push --tagsPush all local tags to origin. By defaultgit pushdoes not push tags.git show v1.0See the tag metadata and the commit it points at.
GitHub from the terminal
`gh` is not git. It is the GitHub API on the command line.
gh repo create <name> --private --source=. --remote=origin --pushCreate a GitHub repo from the current dir, wire up origin, push.gh repo view --webOpen the current repo in your browser.gh pr list --state allList open, closed, and merged PRs for the current repo.gh pr view <num>See a PR in the terminal.--webto open it in your browser.gh pr checkout <num>Pull a teammate’s PR branch locally. Killer feature for testing changes.gh pr review --approve --body "lgtm"Approve a PR from the CLI. Also--request-changesor--comment.gh run list --limit 5Recent GitHub Actions workflow runs for the current repo.gh run watch <id>Block until a run completes, then print the result. Great aftergit push.gh run rerun <id> --failedRerun only the failed jobs of a workflow run. For flaky CI.gh issue list / gh issue createBrowse and create issues from the terminal. Same--webtrick available.gh extension list / gh extension install <repo>List installed gh extensions. Install community extensions from GitHub repos.
Hardening
Make GitHub catch mistakes before they land.
pre-commit installWire up.pre-commit-config.yamlhooks so they run on everygit commit.pre-commit run --all-filesRun all configured hooks against every file in the repo. Use after first install.git commit --no-verifySkip pre-commit hooks for this commit. Almost always the wrong move. Fix the hook..github/CODEOWNERSFile where you assign default reviewers per path glob. Pairs with branch protection.gh api repos/OWNER/REPO/branches/main/protection -X PUT --input rules.jsonSet branch protection rules from a JSON file. Versionable, scriptable.gh secret set SECRET_NAMESet a repository secret for GitHub Actions workflows. Prompts for the value.