Skip to main content
CodingMarble

Interview questions and cheat sheets

Git Commands Cheat Sheet by Task

This Git cheat sheet is organised by what you are trying to do, with copy-ready commands and a clear label on every command that can destroy work. It ends with the reflog, which is how most lost commits get back.

By CodingMarble · Published · 4 min read

Two colleagues discussing ideas at a whiteboard
Photo: ThisisEngineering on Unsplash

Setup and a .gitignore habit

Configure your identity once per machine, because it is written into every commit. Then create a .gitignore before the first commit, not after, so that dependencies, build output and secrets never enter history.

Shell
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main

git init                      # start a repository in this folder
git clone <url>               # copy an existing repository
Shell
# .gitignore
node_modules/
dist/
.next/
.env
.env.local
*.log
.DS_Store

Setting init.defaultBranch means new repositories start on main instead of the older default name. Cloning also sets up origin, the default name for the remote you cloned from, and checks out its default branch. Global settings live in your home folder, while a setting without --global applies only to the current repository.

A file that is already tracked stays tracked even after you add it to .gitignore. Stop tracking it with git rm --cached <file>, then commit. If a secret such as a key in .env was ever committed, removing it later is not enough; rotate the key, because the old commit still contains it.

The daily loop: status, add, commit

Git has three places a change can be: the working folder, the staging area, and the repository. You edit, stage what belongs in the next commit, then commit. The staging area exists so that a commit can contain exactly the changes that belong together, even when you have edited many unrelated files. A commit is a snapshot of the staged content, identified by a hash, with a pointer to its parent.

Shell
git status                    # what changed, what is staged
git add src/app.js            # stage one file
git add -p                    # stage chosen hunks, reviewing each
git diff                      # unstaged changes
git diff --staged             # what the next commit will contain
git commit -m "Fix total when cart is empty"
git commit --amend            # rewrite the last commit (only if not pushed)
  • git add . stages everything in the current folder, so check git status first to avoid committing a stray file.
  • git add -p is the quickest way to keep unrelated edits in separate commits.
  • A good commit message states what changed and why in the first line, in the imperative mood.
  • git commit --amend replaces the last commit; do not use it after pushing a shared branch.

Branching and merging

A branch is a movable label on a commit, so creating one is cheap. Work on a branch per task and merge it back when it is reviewed. git switch is the modern command for changing branches; the older git checkout does the same job and also restores files, which is why newer guides split it into switch and restore.

Shell
git branch                    # list local branches
git switch -c feature/login   # create and move to a new branch
git switch main               # move back
git merge feature/login       # bring the branch into the current one
git branch -d feature/login   # delete a merged branch
git branch -D feature/login   # force delete, even if unmerged (destructive)

If both branches changed the same lines, the merge stops with a conflict. Open the marked files, choose the final text, delete the marker lines, then git add the file and run git commit. git merge --abort returns you to the state before the merge.

Rebase versus merge

Both combine work from two branches. Merge keeps the true history and adds a merge commit. Rebase replays your commits on top of another branch, giving a straight line of history but creating new commits with new hashes.

Shell
git switch feature/login
git rebase main               # replay my commits on top of latest main
git rebase -i HEAD~3          # tidy the last 3 commits: squash, reword, reorder
  • Use rebase to update your own unpublished branch with the latest main, and to clean up commits before opening a pull request.
  • Use merge when the branch is shared, because rebasing public history forces everyone else to repair their copies.
  • The rule to remember: never rebase commits that other people have already pulled.
  • If a rebase goes wrong, git rebase --abort restores the branch.

Undoing mistakes safely

Pick the undo command by asking two questions: has the change been committed, and has it been pushed. The table of options below runs from harmless to destructive.

Shell
git restore --staged app.js   # unstage a file, keep the edits (safe)
git restore app.js            # discard unstaged edits in the file (destructive)
git revert <commit>           # new commit that undoes an old one (safe, public-friendly)
git reset --soft HEAD~1       # undo last commit, keep changes staged
git reset HEAD~1              # undo last commit, keep changes unstaged
git reset --hard HEAD~1       # undo last commit AND delete the changes (destructive)
git clean -n                  # preview untracked files that would be removed
git clean -fd                 # delete untracked files and folders (destructive)
  • git revert is the right tool for a commit that is already pushed, because it adds history rather than rewriting it.
  • git reset moves the branch pointer. The soft and default modes keep your work, and only --hard throws it away.
  • git restore <file> and git clean -fd delete uncommitted work that Git cannot bring back, since it was never saved in a commit.
  • If you must overwrite a remote branch after a rebase, use git push --force-with-lease, which refuses to overwrite commits you have not seen. Plain --force does not check.

Stash and remotes

Stash shelves uncommitted changes so you can switch tasks with a clean working folder. Remotes are named copies of the repository elsewhere, usually called origin.

Shell
git stash push -m "half-done form"   # shelve tracked changes
git stash list
git stash pop                        # reapply the latest and drop it
git stash apply stash@{1}            # reapply a chosen one and keep it

git remote -v                        # show remotes
git fetch                            # download new commits, change nothing locally
git pull --rebase                    # fetch, then replay my commits on top
git push -u origin feature/login     # first push, sets the upstream branch

git fetch is always safe because it only updates your view of the remote. git pull is fetch plus a merge or rebase, so it can change your branch. Stash does not include untracked files unless you add -u.

Reading history: log, diff, blame

History is most useful when you can search it. These commands answer who changed a line, when, and what a commit actually did.

Shell
git log --oneline --graph --decorate -15   # compact branch picture
git log -p -- src/app.js                  # history of one file, with diffs
git log --author="Asha" --since="2 weeks ago"
git show <commit>                         # one commit in full
git diff main..feature/login              # differences between two branches
git blame -L 20,40 src/app.js             # who last changed lines 20-40

Each command answers a different question. git log with a path shows how one file evolved, git show prints one commit with its message and diff, git diff between two branches shows what a merge would bring in, and the double-dot range lists changes reachable from one side. Adding -15 limits the output to the latest fifteen commits.

git log -S 'functionName' finds commits that added or removed that exact text, which is often faster than reading blame output. Blame shows the last editor of a line, not necessarily the author of the idea, so follow it back with git show.

Tags and recovering with reflog

A tag is a permanent name for a commit, normally used for releases. Annotated tags carry a message and author. Tags are not pushed by default, so push each one by name or all at once with git push --tags. Unlike a branch, a tag does not move when you make new commits, which is why release tooling and deployment scripts often point at tags.

Shell
git tag -a v1.2.0 -m "Release 1.2.0"
git push origin v1.2.0
git tag                                  # list tags

The reflog is your local safety net. It records every position HEAD has been in, including commits that no branch points to after a bad reset or a deleted branch. Entries expire after a period, and the log is not shared with the remote, so recover soon and on the same machine.

Shell
git reflog                         # find the lost commit, e.g. HEAD@{3}
git switch -c rescue HEAD@{3}      # put a branch on it
# or, after a bad reset:
git reset --hard HEAD@{1}          # move back to the previous position

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.