Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 78 ยท Troubleshooting and Recipes

Git Recipes and One-Liners

A cookbook of Git recipes with runnable output: squash commits, find a deleted file, compare branches, clean merged branches, archive, count authors, make patches, sync a fork.

Once you know the building blocks of Git, you keep running into the same small jobs: "squash my last five commits", "who deleted this file?", "which branches can I delete?", "send this change as a patch". Each has a short, well-known answer, and most of them are one-liners you can keep in your notes.

This lesson is a cookbook. Every recipe states the problem, gives the command, and runs it on a small repository so you can see the real output. Recipes build on earlier lessons, and we link to them when a recipe needs a deeper explanation. All of the examples use a fixed author and dates so hashes are reproducible, and none of them needs a network.

Most recipes use --format placeholders: %h short hash, %s subject, %an author name, %ad author date. See Log and Show for the full list.

Recipe 1: squash the last N commits into one

You made five tiny "wip" commits and want one clean commit before opening a pull request. The non-interactive way is git reset --soft HEAD~N, which moves the branch back N commits but keeps all their changes staged, then you commit once.

Bash Squash the last 3 commits with reset --soft

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The three commits are replaced by one that contains all three steps. Because the history was rewritten, only do this on commits that are not shared. To keep the first commit's author or message, use interactive rebase and mark commits squash or fixup. To squash everything on a branch since it left main, use git reset --soft $(git merge-base main HEAD).

Recipe 2: find the commit that deleted a file (and restore it)

A file is gone and nobody remembers when. --diff-filter=D limits the log to commits that deleted something.

Bash Who deleted this file and how to get it back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git checkout <commit>^ -- <path> copies the file as it was in the parent of the deleting commit into your working tree and index (it appears as a new staged file). The ^ after the hash means "its first parent". Replace D with A to find where a file was added, or with R for renames.

Recipe 3: what changed between two branches?

Three useful views of "what is on feature that is not on main":

Bash Compare two branches in three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The three-dot form main...feature in git diff compares feature against the merge base, so it shows only the branch's own work (A added, M modified, D deleted). It does not show m.txt, which only exists on main. Two dots in git diff (main..feature) would compare the two tips directly and also show m.txt as deleted. In git log, the meanings are different: main..feature is "reachable from feature but not main", and main...feature with --left-right shows both sides. See Comparing for the rules.

Recipe 4: delete branches that are already merged

Merged branches pile up. List the ones whose tip is already part of main, and delete them (safely, with lowercase -d, which refuses unmerged branches).

Bash Clean up merged branches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

git branch --merged main lists branches whose tip is reachable from main. We filter out main itself with grep -vx main (-x matches whole lines, so a branch called main-fix is not excluded) and feed the rest to git branch -d. The unfinished branch survives. For remote-tracking branches, run git fetch --prune first so deleted remote branches disappear locally. Squash-merged branches are not reachable from main (the squash commit is a different commit), so for those you need -D after checking on the platform.

Recipe 5: export the repository as an archive

git archive creates a tarball or zip of any commit or tag without the .git folder, which is how release tarballs are made. Files marked with the export-ignore attribute (see .gitattributes) are left out.

Bash Create a release archive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The --prefix puts everything inside a folder named app-1.0.0/, which is what people expect when they unpack a release. The tests/ folder is missing because of export-ignore, and .git is never included. The .gitattributes file itself is included.

Recipe 6: statistics: commits per author, files by activity

git shortlog summarizes the log per author. Add -sn to get counts sorted from most to fewest, and -e to include emails. Note: it needs a revision (like HEAD) when its input is not a terminal; the sandbox always needs it.

Bash Count commits by author and find hot files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Ada has three commits, Bob and Cleo one each. The second pipeline prints just the file names from every commit (--format= with nothing after the equals sign suppresses the commit header), so main.py shows four commits against one for util.py. Files that change in almost every commit are called hotspots and are good places to look for design problems. For a quick leaderboard you may see git shortlog -sne in blog posts; it adds email addresses and treats the same person with two emails as two authors unless you configure a .mailmap file.

Recipe 7: export commits as patches and apply them

A patch is a text file describing a commit. git format-patch writes one file per commit (including author, date and message), and git am applies them on another clone. This is how the Linux kernel and many mailing-list based projects work, and it needs no shared remote.

Bash Send commits as a patch series with format-patch and am

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The patch files are numbered in order. They record the author (Ada) while git am records the person applying them as committer (Bob), and the commit message comes along, so no information is lost. If a patch does not apply cleanly, git am stops; fix the conflict and run git am --continue, or give up with git am --abort. A single change without commits can be turned into a patch with git diff > change.patch and applied with git apply change.patch (no commit is created).

Recipe 8: bring a fork up to date

You forked a project and the original (upstream) has moved on. Fetch it and fast-forward your main; --ff-only makes the command fail loudly if you had committed to main by accident, instead of creating a surprise merge.

Bash Sync a fork with upstream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

If --ff-only fails with "Not possible to fast-forward, aborting", your main has commits of its own. Move them to a topic branch first (see Fixing Common Git Mistakes) and reset main to upstream/main. More background is in Forks and Upstreams.

Recipe 9: small one-liners worth keeping

These need no demo repository of their own, but here they are on one, so you can see each result.

Bash A handful of useful one-liners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Notes on selected lines: rev:path syntax (HEAD~2:a.txt) prints a file as it was; git describe --tags --abbrev=0 finds the nearest tag reachable from HEAD; git branch --contains and git tag --contains answer "has this commit shipped?"; git restore --source replaces a file with its version from any commit, and it is a destructive command for uncommitted edits to that file. Always run git clean -n (dry run) before -f, because untracked files cannot be recovered from Git.

More recipes, without a demo

These need a remote or an interactive tool, so they are read-only here:

Terminal
# Delete a remote branch
git push origin --delete old-branch

# Remove local references to branches deleted on the remote
git fetch --prune

# Rename the current branch and fix the upstream
git branch -m new-name
git push -u origin new-name

# Undo "git add ." for everything
git restore --staged .

# See what a pull would bring in, before pulling
git fetch && git log --oneline HEAD..@{u}

# Commits you have not pushed yet
git log --oneline @{u}..HEAD

# Which commit introduced a bug? (binary search, see the bisect lesson)
git bisect start HEAD v1.0 && git bisect run ./test.sh

@{u} is shorthand for "the upstream of the current branch". The Bisect lesson shows the last recipe in action, and Aliases shows how to turn your favourite recipes into short commands such as git cleanup or git last.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does git reset --soft HEAD~3 followed by git commit do?

    --soft moves the branch pointer back but keeps the changes staged, so one new commit holds them all.
  2. 2. Which command finds the commit that deleted notes.txt?

    --diff-filter=D keeps only commits where the listed path was deleted. Blame needs a file that still exists.
  3. 3. What does git diff main...feature (three dots) compare?

    The three-dot form diffs from the common ancestor, so it shows only what the feature branch changed.
  4. 4. Why does git branch -d refuse to delete a squash-merged branch?

    A squash merge copies the changes into one new commit, so the original commits are not ancestors of main and Git considers the branch unmerged.
  5. 5. Which pair of commands moves commits between repositories without a shared remote?

    format-patch writes one patch file per commit with author and message; am applies them as commits in another repository.

Summary

  • Squash with git reset --soft HEAD~N plus a commit; find deleted files with git log --diff-filter=D -- path and restore with git checkout <commit>^ -- path.
  • Compare branches with git diff main...feature (merge base) and git log main..feature.
  • Clean merged branches with git branch --merged main | grep -vx main | xargs -r git branch -d.
  • git archive makes release tarballs without .git; export-ignore excludes files.
  • git shortlog -sn HEAD counts commits per author; git log --format= --name-only | sort | uniq -c finds hotspots.
  • git format-patch and git am transfer commits as files; git fetch upstream plus merge --ff-only syncs a fork.
  • Always dry-run destructive commands such as git clean -n.

Next: Troubleshooting: Errors and What They Mean