- Mon 16 November 2026
- 37 min read
- Linux
- #git, #version-control, #lazygit, #worktree, #cherry-pick, #rebase, #signing, #openpgp, #smartcard, #oct-git, #ssh, #forgejo, #fedora, #freebsd

Table of Contents
- Table of Contents
- The Mental Model
- The Basics, Briefly
- A Configuration Worth Having
- Merge or Rebase
- Recovering From Mistakes
- Cleaning Up Before You Share
- Cherry-Picking
- Worktrees: Several Branches at Once
- Finding Things in History
- Signing Commits
- lazygit: The Same Ideas, Fewer Keystrokes
- Housekeeping
- What This Article Doesn’t Cover
- The Command Card I Actually Use
- Conclusion
- Further Reading
Git is one of those tools everybody uses and few people enjoy. There is no shortage of tutorials, but they all seem to cover the same twenty minutes: init, add, commit, push, a branch, a merge conflict, done. After that you are on your own, and “on your own” usually means a Stack Overflow answer from 2014 that tells you to git stash your way out of everything.
The part that is missing is the middle. Not Git internals, not plumbing commands, just the dozen features that turn Git from something you survive into something that works for you. This article starts with the basics, because the advanced parts only make sense on top of a correct mental model. Then it gradually gets deeper. Skip ahead if you already know where your HEAD is.
The short version: commits are snapshots, branches are movable labels, and almost nothing you have committed is lost. Once that clicks, worktrees, cherry-picks and rebases stop being scary. Sign what you publish, and remember that rewriting history drops signatures unless you ask Git to sign again.
Everything in this article was checked against Git 2.56.1 on Fedora 45. The examples all come from one small test repository, a toy INI parser called inigo, so the commit IDs in one section match the ones in the next. Nothing here needs a bleeding-edge Git, but a few features have minimum versions: --force-if-includes needs Git 2.30, SSH signing 2.34, zdiff3 2.35, push.autoSetupRemote 2.37 and --update-refs 2.38. If you are on an older enterprise distribution, check git --version first.
The Mental Model
Most Git confusion comes from one wrong picture: that Git stores changes. It doesn’t, at least not conceptually. A commit is a snapshot of the whole tree, plus metadata (author, committer, date, message) and a pointer to its parent commit or commits. Diffs are computed when you ask for them.
From that, everything else follows:
- Commits form a graph. Each commit points back to its parent, and a merge commit has two parents. The history is a directed acyclic graph, not a list.
- A commit’s ID is a hash of its content and its parents. Change anything, the message, the author date, a parent, and you get a different commit with a different ID. This is why “rewriting history” really means “creating new commits and moving labels to them”.
- A branch is a label pointing at one commit. That is all. Creating a branch costs almost nothing: Git just stores a commit ID under a name. When you commit on a branch, the label moves forward to the new commit.
HEADis where you are. Usually it points at a branch, which points at a commit. If it points directly at a commit, you are in “detached HEAD” state, which sounds alarming and isn’t.- The index (staging area) is the next commit being prepared.
git addcopies content into it,git committurns it into a snapshot.
So there are three places a file can differ: your working directory, the index and the last commit (HEAD). git diff compares working directory to index, git diff --staged compares index to HEAD. Once you have that triangle in your head, most commands are just ways of moving content between its corners.
The Basics, Briefly
If you have used Git before, skim this. If you haven’t, this is the minimum set:
git clone https://git.example.org/me/inigo.git
cd inigo
git status # what changed, what is staged
git diff # unstaged changes
git add -p # stage changes hunk by hunk
git diff --staged # what will be committed
git commit # opens the editor for a message
git log --oneline --graph # history as a graph
git push
Two habits from that list are worth adopting from day one.
Use git add -p instead of git add .. It walks through every change and asks whether to stage it. It’s the cheapest code review you will ever get, and it is where you notice the debug print and the commented-out block before they end up in a commit.
Use switch and restore instead of checkout. git checkout does two unrelated jobs: switching branches and overwriting files. That’s how people lose work by typing a filename where they meant a branch. The newer commands split those jobs:
| Task | Old | New |
|---|---|---|
| Switch to a branch | git checkout main |
git switch main |
| Create and switch | git checkout -b feature |
git switch -c feature |
| Go back to the previous branch | git checkout - |
git switch - |
| Discard working copy changes | git checkout -- file |
git restore file |
| Unstage a file | git reset HEAD file |
git restore --staged file |
git checkout still works and will keep working. I just find the new commands harder to misuse.
A Configuration Worth Having
Git’s defaults are conservative and mostly reflect decisions made for the Linux kernel workflow in 2005. A handful of settings make daily work noticeably better. This is roughly what I set on a new machine:
git config --global init.defaultBranch main
git config --global pull.ff only
git config --global push.autoSetupRemote true
git config --global fetch.prune true
git config --global merge.conflictStyle zdiff3
git config --global diff.algorithm histogram
git config --global rerere.enabled true
git config --global rebase.autoSquash true
git config --global rebase.updateRefs true
git config --global branch.sort -committerdate
What each one does:
| Setting | Effect |
|---|---|
pull.ff only |
git pull only fast-forwards. If your branch and the remote have diverged, it stops and lets you decide between merge and rebase, instead of silently creating a merge commit. |
push.autoSetupRemote |
The first git push on a new branch sets the upstream. No more --set-upstream origin feature error message. |
fetch.prune |
Remote-tracking branches that were deleted on the server disappear locally on fetch. |
merge.conflictStyle zdiff3 |
Conflict markers also show the common ancestor. You see what both sides changed, not just what they ended up with. This one setting made conflicts much less confusing for me. |
diff.algorithm histogram |
Often produces more readable diffs than the default, especially when code was moved around. |
rerere.enabled |
Git remembers how you resolved a conflict and reapplies the resolution next time. More on that in the next section. |
rebase.autoSquash |
git rebase -i automatically moves fixup! commits to the right place. |
rebase.updateRefs |
When rebasing a stack of branches, Git moves every branch label in the stack, not only the one you are on. |
branch.sort -committerdate |
git branch lists recently used branches first. |
Different Identities per Directory
If you use the same machine for work and private projects, you need two identities. The clumsy way is to remember git config user.email in every new clone. The better way is conditional includes:
# ~/.gitconfig
[user]
name = Christian Hofstede-Kuhn
email = private@example.org
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work
# ~/.gitconfig-work
[user]
email = me@work.example.com
Every repository under ~/work/ picks up the work address automatically. The trailing slash matters: it means “this directory and everything below it”. The same trick works for different signing keys, which becomes relevant later.
Merge or Rebase
This is the oldest argument in Git, and I don’t think there is one right answer. Here is what each does and when I use it.
Merge creates a new commit with two parents. History stays exactly as it happened, including every “wip” and “fix typo” commit. Nothing is rewritten, so nothing that anybody else has can break.
Rebase takes your commits and replays them on top of another commit, creating new commits with new IDs. History becomes linear and easier to read. The old commits still exist for a while, as the next section shows, but your branch no longer points at them.
My rule is simple: rebase what is still mine, merge what is shared. Before I open a pull request, I rebase my feature branch onto the current main and clean it up. Once others have built on top of a branch, I don’t rewrite it any more. The PR itself is then merged on the forge.
When you do have to force-push a rebased branch, never use a plain --force:
git push --force-with-lease --force-if-includes
--force-with-lease refuses to overwrite the remote branch if it changed since you last fetched it, so you don’t destroy a colleague’s push. --force-if-includes closes a gap in that check: a background git fetch from your editor updates your remote-tracking refs, and then --force-with-lease alone would happily overwrite commits you never actually looked at. Together they are what --force should have been. I have an alias for it:
git config --global alias.pushf "push --force-with-lease --force-if-includes"
rerere: Resolve Each Conflict Once
Merges and rebases both produce conflicts, and a long-lived branch tends to produce the same conflict again and again. rerere stands for “reuse recorded resolution”. With rerere.enabled set, Git saves the conflict and your resolution whenever you resolve one. In inigo, two branches reworded the README title differently. The first merge conflicts as usual, and Git records it:
CONFLICT (content): Merge conflict in README.md
Recorded preimage for 'README.md'
Automatic merge failed; fix conflicts and then commit the result.
After I resolve and commit it, Git prints Recorded resolution for 'README.md'. When I throw that merge away and merge again, the same conflict gets my old resolution automatically:
CONFLICT (content): Merge conflict in README.md
Resolved 'README.md' using previous resolution.
Automatic merge failed; fix conflicts and then commit the result.
This matters most when you rebase a long-lived branch repeatedly, or when you test-merge a branch, throw the merge away and do it again later. Git still stops and marks the merge as conflicted, so you review the result and git add it yourself. It just saves you the typing.
Recovering From Mistakes
Before the sections that rewrite history, the safety net. Rebases, resets and amends create new commits and move labels. The old commits stay in the object database until garbage collection removes them, and that takes a while. Once something has been committed, it is very hard to lose it by accident.
The Reflog
Git records every movement of HEAD and of every branch in the reflog. That is your undo history. inigo has a parser branch and a cli branch stacked on top of it, and here is the reflog right after rebasing them in the next section:
$ git reflog
c4137b3 HEAD@{0}: rebase (finish): returning to refs/heads/cli
c4137b3 HEAD@{1}: rebase (pick): cli: add --config option
9b6891a HEAD@{2}: rebase (pick): parser: support include files
70e4cd2 HEAD@{3}: rebase (fixup): parser: parse sections and keys
43cfa17 HEAD@{4}: rebase (pick): parser: parse sections and keys
ecf2e5a HEAD@{5}: rebase (start): checkout main
c8be862 HEAD@{6}: checkout: moving from main to cli
Botched the rebase? Find the entry from just before rebase (start) and reset to it:
git reset --hard HEAD@{6}
Branches have their own reflog too, and that is usually the easier handle. cli@{1} is where cli pointed before its last change. A rebase only moves the branch once, when it finishes, so after a rebase cli@{1} is the old version of the branch:
git reset --hard cli@{1}
You may have seen ORIG_HEAD recommended for this. Rebase, merge and reset do store the previous position there, but every git reset overwrites it. If you ran a reset during the rebase, for example to split a commit in an edit step, ORIG_HEAD points somewhere in the middle of the rebase, not at the old branch. I tested that, and cli@{1} was still correct while ORIG_HEAD was not. The branch reflog is the form I trust.
Undoing a Stacked Rebase
One catch if you follow my configuration and set rebase.updateRefs. A rebase of a stack moves several branches, and resetting the one you are on restores only that one. In inigo, cli is stacked on parser. To undo the rebase, both need to go back:
git reset --hard cli@{1}
git branch -f parser parser@{1}
The output of the rebase lists every ref it updated, so you know which branches to restore.
What the Reflog Doesn’t Know
The reflog is local and not unlimited. By default, entries are kept for 90 days. Entries for commits that are no longer reachable from the current tip of that ref, such as the old commits after a rebase, expire after 30 days. That is plenty of time to notice a mistake, but it’s not a backup.
And it only knows about commits. Changes you never committed or stashed are not in the reflog. git reset --hard and git restore on uncommitted work really do destroy it.
The Three Kinds of Reset
git reset moves the current branch to another commit. The flag decides what happens to the index and your files:
| Command | Branch moves | Index | Working files |
|---|---|---|---|
git reset --soft <c> |
yes | unchanged | unchanged |
git reset --mixed <c> (default) |
yes | reset to <c> |
unchanged |
git reset --hard <c> |
yes | reset to <c> |
reset to <c> |
git reset --soft HEAD~3 is a quick way to squash the last three commits into one: the branch moves back, everything stays staged, and you commit again.
For changes that are already pushed and shared, don’t reset at all. Use git revert, which creates a new commit that undoes an old one. History stays intact and nobody else’s clone breaks.
Cleaning Up Before You Share
Nobody writes a feature in a perfect sequence of commits. You implement something, find a bug in a commit three steps back, fix it, rename a function, fix the rename. The history ends up as a diary. Reviewers don’t need your diary. They need a sequence of changes that each make sense on their own.
Interactive rebase is the tool for that, and fixup commits make it painless.
Fixup Commits and Autosquash
In inigo I have two branches. parser adds the INI parser in two commits, and cli builds on top of it. While working on cli, I noticed that the first parser commit splits key = value on every = and doesn’t strip whitespace. Instead of a “fix parser bug” commit, I tell Git which commit the fix belongs to:
git add -p
git commit --fixup=":/^parser: parse sections"
:/text selects the most recent commit whose message matches that regular expression, which saves looking up the ID. The ^ anchor matters: without it, a second fixup for the same commit would match the first fixup! parser: parse sections and keys, because that is the more recent commit containing the text. Git creates a commit named fixup! parser: parse sections and keys. Meanwhile main gained a CI commit, so the branch is out of date as well:
c8be862 (HEAD -> cli) fixup! parser: parse sections and keys
1d549e5 cli: add --config option
984a6c3 (parser) parser: support include files
0417e83 parser: parse sections and keys
One command fixes both:
git rebase -i main
With rebase.autoSquash set, the editor opens with the fixup commit already moved right after its target and marked fixup. Save, close, and the fix is folded into the original commit, on top of the current main:
c4137b3 (HEAD -> cli) cli: add --config option
9b6891a (parser) parser: support include files
70e4cd2 parser: parse sections and keys
ecf2e5a (main) ci: run tests on FreeBSD
Every commit has a new ID. These are new commits, as described in the mental model.
There are variations. git commit --fixup=amend:<commit> also replaces the target’s commit message, and git commit --squash=<commit> keeps both messages for you to merge.
Stacked Branches With --update-refs
Look at that output again: parser moved too, even though I rebased while on cli. Before --update-refs, rebasing cli would have left parser pointing at the old commits, and you had to fix up the labels by hand. With rebase.updateRefs set, Git moves every local branch that points into the rebased range. I then force-push both branches, and both pull requests are up to date.
Two side effects are worth knowing, and I tested both. First, “every local branch” includes a backup branch you created just before the rebase as a safety net. It moves along with the others, so it no longer points at the old commits. The reflog is the better safety net anyway. Second, a branch that is checked out in another worktree is not moved. The todo list shows it as a comment:
# Ref refs/heads/parser checked out at '/home/me/src/inigo-parser'
That is reasonable, because moving a branch under another worktree would leave that worktree in a confusing state. But it means you rebase that branch separately.
Comparing Two Versions of a Branch
After a rebase, a reviewer will want to know what actually changed since the last version. git diff between the old and new branch tip is useless, because it includes everything that changed on main in between. git range-diff compares the two series commit by commit:
git range-diff main cli@{1} cli
That compares main..cli@{1}, the old version from the branch reflog, with main..cli, the new one. For the rebase above:
1: 0417e83 ! 1: 70e4cd2 parser: parse sections and keys
@@ parser.py
+ section = line[1:-1]
+ result[section] = {}
+ elif "=" in line:
-+ key, value = line.split("=")
++ key, value = (s.strip() for s in line.split("=", 1))
+ result[section][key] = value
return result
2: 984a6c3 ! 2: 9b6891a parser: support include files
@@ Commit message
## parser.py ##
@@ parser.py: def parse(text):
- key, value = line.split("=")
+ key, value = (s.strip() for s in line.split("=", 1))
result[section][key] = value
return result
+
3: 1d549e5 = 3: c4137b3 cli: add --config option
4: c8be862 < -: ------- fixup! parser: parse sections and keys
It takes a moment to read, because it is a diff of diffs. The first column of - and + says what changed between the two versions of the patch. The second column is the patch itself. ! marks a modified commit: the first one now contains the fix. The second commit’s own change is the same, but its context lines changed, so it shows up as modified too. = means unchanged apart from its parent, and < marks a commit that only exists in the old series, here the fixup that was folded in.
The CI commit from main doesn’t appear at all, which is the point. I run range-diff before every force-push to make sure the rebase did what I wanted, and nothing else.
Cherry-Picking
git cherry-pick takes the change introduced by one commit and applies it as a new commit on the current branch. That is the entire feature, and it’s more useful than it sounds.
The classic case is a backport. inigo has a release-1.0 branch. On main, I fixed the parser to skip blank lines and comments, and that fix also belongs in the release branch, but the documentation work on main doesn’t. First, which commits are on main but not on the release branch?
$ git cherry -v release-1.0 main
+ 75f6c7c6c6418f610cf645165ecf4f819d21cef6 parser: skip blank lines and comments
+ 9e8db67b8e3b86546481f3c9d8ee42e9402e806b docs: describe include files
Then pick the fix:
git switch release-1.0
git cherry-pick -x 75f6c7c
Always use -x for backports. It appends a line to the commit message that records where the change came from:
parser: skip blank lines and comments
(cherry picked from commit 75f6c7c6c6418f610cf645165ecf4f819d21cef6)
Six months later, when somebody asks whether release-1.0 has the fix for that CVE, a git log --grep answers the question.
git cherry compares patches, not commit IDs, so after the pick it recognizes the fix as already present, even though the commit on release-1.0 has a different ID:
$ git cherry -v release-1.0 main
- 75f6c7c6c6418f610cf645165ecf4f819d21cef6 parser: skip blank lines and comments
+ 9e8db67b8e3b86546481f3c9d8ee42e9402e806b docs: describe include files
Ranges and Conflicts
You can pick several commits at once:
git cherry-pick A..B # everything after A, up to and including B
git cherry-pick A^..B # including A itself
The first form excludes A, which trips people up every time. When a pick conflicts, Git stops in the middle of the sequence, exactly like a rebase. Resolve the conflict, git add the files, and then:
git cherry-pick --continue # carry on with the next commit
git cherry-pick --skip # drop this commit and carry on
git cherry-pick --abort # go back to where you started
When Not to Cherry-Pick
A cherry-pick creates a new commit with the same change and a different ID. If both branches are later merged, Git usually copes, but you end up with the same change twice in history, and conflicts around it get more confusing.
So cherry-picking is a tool for branches that will never be merged into each other: release branches, stable branches, a downstream fork. For two feature branches that will both end up in main, the better approach is to put the shared change into its own branch, merge it first, and rebase the others on top. Where a project has long-lived maintenance branches, some prefer to commit the fix to the oldest branch and merge it forward instead. Both work. What doesn’t work well is cherry-picking back and forth between branches that later meet.
Cherry-picking a merge commit needs -m 1 to tell Git which parent to diff against. If you find yourself doing that regularly, it is probably a sign the branching model is fighting you.
Worktrees: Several Branches at Once
This is the feature I wish somebody had shown me ten years earlier.
The usual situation: you are in the middle of a feature, with half-finished changes and a build directory full of artifacts. A colleague asks you to review a pull request, or production needs a hotfix. Your options without worktrees are all bad. You stash your changes, switch branch, rebuild everything, do the other thing, switch back, rebuild again, pop the stash and hope it applies cleanly. Or you clone the repository a second time and keep two copies in sync by hand.
A worktree is an additional working directory attached to the same repository. Each worktree has its own checked-out branch, its own index and its own files. They all share the same object database, refs and configuration. Creating one takes a second and no network access. Say release-1.0 of inigo needs a hotfix while I’m working on main:
git worktree add ../inigo-hotfix -b hotfix release-1.0
That creates the directory ../inigo-hotfix, a new branch hotfix starting at release-1.0, and checks it out there. My original directory is untouched, including the uncommitted changes and the build artifacts. cd over, fix, commit, push, and go back.
$ git worktree list
/home/me/src/inigo 9409eec [main]
/home/me/src/inigo-hotfix d4bd468 [hotfix]
When you are done:
git worktree remove ../inigo-hotfix
remove refuses if the worktree has uncommitted changes, which is the right default. If you deleted a worktree directory with rm -rf, git worktree prune cleans up the leftover administrative data.
Reviewing Pull Requests in a Worktree
Forgejo, Gitea and GitHub all expose pull requests as refs under refs/pull/<number>/head. That makes a review worktree a two-liner:
git fetch origin pull/104/head:pr-104
git worktree add ../inigo-pr-104 pr-104
Now I can build and run the PR next to my own work, without touching it. If I only want to look, I skip the local branch and use a detached worktree. That needs a plain fetch first, which leaves the PR head in FETCH_HEAD:
git fetch origin pull/104/head
git worktree add --detach ../inigo-pr-104 FETCH_HEAD
What Is Shared and What Isn’t
This table is the part most worktree introductions skip, and it explains every surprise I have had with them:
| Shared between worktrees | Separate per worktree |
|---|---|
| Commits and all other objects | HEAD, the checked-out branch |
| Branches, tags, remote refs | The index (staging area) |
Repository configuration (.git/config) |
The working files |
| Stashes | Untracked and ignored files, build output |
| Hooks | Bisect and rebase state |
The most visible consequence: a branch can only be checked out in one worktree at a time. Git refuses otherwise, and tells you where:
fatal: 'hotfix' is already used by worktree at '/home/me/src/inigo-hotfix'
This is a feature. Two working directories committing to the same branch would be chaos. It is also why --update-refs leaves such a branch alone. The other consequences:
- A commit in one worktree is immediately visible in all others. No fetch, no push. You can cherry-pick from the hotfix worktree into the main worktree right after committing.
- The stash is shared. A
git stashin one worktree shows up ingit stash listin all of them. That surprised me the first time. With worktrees I rarely stash at all any more, which is half the point. - Build artifacts and dependencies are not shared. Each worktree needs its own
node_modules,target/or virtualenv. That costs disk space and an initial build, but it is also why switching contexts no longer invalidates your build. - Configuration is shared by default. If one worktree needs different settings, enable
extensions.worktreeConfigand usegit config --worktree.
How I Lay Them Out
I keep worktrees as siblings of the main checkout, named after the repository and the branch: inigo, inigo-hotfix, inigo-pr-104. Some people prefer a bare repository with every branch as a worktree inside it. That works too, but sibling directories keep the main checkout a normal repository that every tool understands.
For a worktree on a removable disk or a network share, lock it, so that prune doesn’t clean it up while the disk is not mounted:
git worktree lock --reason "on usb disk" ../inigo-usb
Finding Things in History
Git’s history is a database, and the query tools are better than most people know.
Who changed this line, and why? git blame is the obvious answer, but the useful flags are less known. -w ignores whitespace changes, and -C follows lines that were moved or copied from other files. For mass reformatting commits that pollute every blame, put their IDs in a file and tell Git to skip them:
git config blame.ignoreRevsFile .git-blame-ignore-revs
When did this string appear or disappear? The pickaxe search finds commits that changed the number of occurrences of a string:
git log -S 'split("=", 1)' --oneline
How did this function evolve? git log -L shows the history of a line range or a function:
git log -L :parse:parser.py
Which commit broke it? git bisect does a binary search through history. Some time after the backport, inigo stopped handling values that contain an =, like url = a=b. A test script that exits 0 for good and non-zero for bad lets bisect run unattended:
#!/bin/sh
# test-equals.sh
python3 -c 'import parser; assert parser.parse("[s]\nurl = a=b")["s"]["url"] == "a=b"'
git bisect start main release-1.0 # bad, then good
git bisect run ../test-equals.sh
git bisect reset
Bisect checks out commits, runs the script and narrows the range. The interesting part of the output:
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[9368001702033b723bdf2466d1d38f6afa4a2cee] parser: tidy up
running '../test-equals.sh'
9368001702033b723bdf2466d1d38f6afa4a2cee is the first 'bad' commit
commit 9368001702033b723bdf2466d1d38f6afa4a2cee
[author and date lines]
parser: tidy up
parser.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
bisect found first 'bad' commit
“Tidy up” quietly went back to splitting on every =. Commits with honest, specific messages make this output much more useful.
The exit code convention has one more value worth knowing. Exit code 125 tells bisect to skip the current commit, which is what makes bisect run usable when some commits in the range don’t build: have the script return 125 when the build fails. Codes from 1 to 127, apart from 125, mean bad, and anything above 127 aborts the run.
Signing Commits
On my Forgejo instance, the branch protection for main and my article branches rejects unsigned commits. That is a deliberate choice, and to me signing is the most underexplained topic in Git.
What a Signature Proves, and What It Doesn’t
The author and committer fields of a commit are just text. Anybody can run git config user.name "Linus Torvalds" and commit as him. A forge that shows the author’s avatar next to that commit is not lying, exactly, but it is showing you something nobody checked.
A signature proves that the commit was created by someone holding a particular private key. Since the commit ID covers the whole content and the complete history, a signature on a commit also protects everything that commit points to.
What it does not prove:
- That the code is correct or safe.
- That the key belongs to the person you think it does. That is a separate question, answered by how you got the public key.
- That the author field is accurate. The signature covers the author field, but nothing stops a key holder from writing someone else’s name into it.
So signing is about provenance. Combined with a forge that refuses unsigned pushes, it means a leaked access token or SSH push key is not enough to push code to my repositories. The attacker would also need my signing key, and in my case that key lives on a hardware token that requires a PIN and a touch.
A stolen account password is a different story. Somebody who can log in to the forge can register their own signing key with my email address, and their commits then show as verified. Signing only helps against that if the account itself is protected with a second factor.
Three Signature Formats
Git supports three formats, selected with gpg.format:
gpg.format |
Program | Key |
|---|---|---|
openpgp (default) |
gpg, or a compatible replacement such as oct-git |
OpenPGP key, possibly on a smartcard |
ssh |
ssh-keygen |
Any SSH key, including FIDO2 keys |
x509 |
gpgsm |
X.509 certificate, for corporate PKI |
If you have no signing setup at all yet, SSH signing is the easiest start, because you probably already have an SSH key:
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
For verification, SSH has no keyring or web of trust, so Git needs a file that maps identities to keys:
mkdir -p ~/.config/git
echo "me@example.org $(cat ~/.ssh/id_ed25519.pub)" >> ~/.config/git/allowed_signers
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
Then:
$ git commit -S -m "signed"
$ git verify-commit HEAD
Good "git" signature for me@example.org with ED25519 key SHA256:GPiOP4A1Oi7Chq0pqtPVhZSycN7gbFBAJeD/J7PoiAY
OpenPGP on a Smartcard With oct-git
I sign with OpenPGP, on a hardware token. But not with GnuPG.
Git doesn’t actually need GnuPG. It calls whatever program gpg.program points to, passes the data on standard input and expects a signature in GnuPG’s output format. oct-git from the OpenPGP Card project implements exactly that subset and nothing else, and talks directly to the OpenPGP card. No gpg-agent, no scdaemon, no keyring on disk.
I maintain the packages for it, together with the other two tools of the project, oct and openpgp-card-ssh-agent. On FreeBSD it is in the ports tree as security/openpgp-card-tools-git. For Fedora 44, 45 and Rawhide, I build them in my COPR repository larvitz/openpgp-card:
# Fedora
sudo dnf copr enable larvitz/openpgp-card
sudo dnf install openpgp-card-tools openpgp-card-tools-git
# FreeBSD
pkg install openpgp-card-tools openpgp-card-tools-git
The FreeBSD ports are new, so depending on your package branch pkg may not offer them yet. In that case, build them from the ports tree.
Then point Git at it:
git config --global gpg.program oct-git
git config --global user.signingkey <fingerprint>
oct-git --store-card-pin
The fingerprint is the signing key on the card, as shown by oct status, in hex without spaces. My article on the Rust OpenPGP card stack covers the card setup, PIN storage, touch confirmation and the FreeBSD pinentry wrapper in detail, so I won’t repeat that here. Two Git-specific traps are worth knowing, though.
Set user.signingkey to a fingerprint. If it is unset, Git passes your committer name and email to the signing program as the key to use. GnuPG looks that up in its keyring. oct-git expects a fingerprint and fails with an unhelpful parse error:
Odd number of digits
That cost me some head-scratching the first time. Setting the key explicitly, globally or per repository, fixes it.
GnuPG’s scdaemon can hold the card exclusively. If GnuPG is also installed and something triggered it, oct-git may report that no card was found while the token is plugged in and blinking happily. gpgconf --kill scdaemon releases it. The card stack article has the permanent fix.
Rewriting History Drops Signatures
This is the part that bites people who sign only now and then, which includes me. I keep commit.gpgsign off and sign explicitly with git commit -S, because not every scratch repository needs a PIN prompt.
But a rebase, an amend or a cherry-pick creates new commits, and new commits are only signed if Git is told to sign them. I tested it:
orig: G
after plain rebase: N
after rebase -S: G
cherry-pick: N
G means a good signature, N means no signature. The original commit was signed. A plain git rebase produced an unsigned copy, and my forge would have rejected the push. The same is true for cherry-pick. The fix is to pass -S to those commands as well (git rebase -S, git cherry-pick -S, git commit --amend -S), or to enable signing per repository where it matters:
git config commit.gpgsign true
git config tag.gpgsign true
With a smartcard and touch confirmation, a rebase of ten commits means ten touches. That’s a reasonable price, and it is a nice reminder that you are rewriting ten commits.
Checking Signatures
To see signatures in the log:
git log --show-signature -1
git log --format='%h %G? %GS %s'
The %G? placeholder is the useful one for scripts. G is good, N is unsigned, B is bad, E means the signature could not be checked (often a missing public key), and U is a good signature from a key with unknown trust. git verify-commit and git verify-tag exit non-zero if verification fails, so they work in CI.
Sign tags too. A signed release tag is how users can check that v1.0 is really the commit you released:
git tag -s v1.0 -m "Release 1.0" release-1.0
git verify-tag v1.0
On the forge side, upload your public key to your account. Forgejo, Gitea, GitLab and GitHub then show a verified badge on signed commits, as long as the committer email matches an address on the account. Forgejo’s branch protection has a “require signed commits” option, which is what rejects my unsigned pushes.
lazygit: The Same Ideas, Fewer Keystrokes
Everything above works on the command line, and I think it is worth knowing it there first. But for the more complex operations, I regularly reach for lazygit, a terminal UI for Git written in Go. It doesn’t replace understanding Git. It makes the operations from this article fast enough that I actually use them, instead of telling myself I’ll clean up the history later.
The interesting part is how directly lazygit maps to the concepts above:
| Concept from this article | In lazygit |
|---|---|
git add -p |
Open a file, stage single lines or hunks with <space> |
| Fixup commits and autosquash | F on a commit creates a fixup! commit for it, S applies them |
| Finding the commit to fix up | <ctrl+f> in the files view finds the commit your current changes build on |
| Interactive rebase | i starts one, then s squash, f fixup, d drop, e edit, directly on the commit list |
| Cherry-pick | C copies commits, V pastes them onto the checked-out branch |
| Worktrees | w on a branch creates a worktree for it and switches to it |
| Reflog and undo | z undoes the last Git operation by looking at the reflog |
| Bisect | b on a commit opens the bisect options |
The keys are from lazygit’s own keybinding documentation. Press ? in any panel to see what is available there.
Two features go beyond what I would comfortably do by hand. Custom patches let you pick individual hunks out of an old commit and move them into a new commit, into the index or out of the commit entirely. On the command line, that is an interactive rebase with edit, a partial reset, add -p and a careful rebase --continue. Amending an older commit with A is a rebase in the background, too, and lazygit handles it for you.
The undo comes with the same caveat as the reflog. Lazygit’s documentation says it plainly: undo only considers commits, not changes in your working tree. Discarded uncommitted changes are gone in lazygit just as they are with git restore.
Lazygit drives the normal git binary, so your configuration applies, including gpg.program. That also means the signing caveat from above applies: commits that lazygit rewrites during a rebase are only signed if signing is enabled for the repository, for example with commit.gpgsign.
On FreeBSD it is a pkg install lazygit away. For Fedora, the project’s README points to the dejan/lazygit COPR repository:
# Fedora
sudo dnf copr enable dejan/lazygit
sudo dnf install lazygit
# FreeBSD
pkg install lazygit
Then run lazygit inside any repository.
Housekeeping
Large repositories slow down over time as loose objects pile up. Git cleans up opportunistically, but you can also hand that job to a scheduler:
git maintenance start
This registers the repository and schedules background tasks, such as prefetching from remotes and repacking objects. Git picks the platform’s scheduler: systemd user timers on Linux where available, cron on the BSDs and on Linux without systemd, launchd on macOS and the task scheduler on Windows. git maintenance stop undoes it. For the occasional manual cleanup, git gc is still there.
What This Article Doesn’t Cover
Git is big, and I deliberately left out several things:
- Submodules and subtrees. Both solve “repository inside a repository”, both come with sharp edges, and both deserve their own article.
- Large files. Git LFS, partial clones and sparse checkouts matter for monorepos and game assets. I have neither.
- Rewriting entire histories. Removing a leaked secret from every commit is a job for
git filter-repo, and the more important step is rotating the secret, because anybody who cloned already has it. - Hooks. Useful for local checks, but they are not distributed with the repository and are easily bypassed. Enforcement belongs on the server or in CI.
- Plumbing commands.
cat-file,hash-objectand friends are fascinating if you want to see how the object store works. Pro Git’s internals chapter does that better than I could.
The Command Card I Actually Use
| Task | Command |
|---|---|
| Stage changes interactively | git add -p |
| Unstage a file | git restore --staged <file> |
| Safe force-push | git push --force-with-lease --force-if-includes |
| Find a lost commit | git reflog |
| Undo the last rebase of a branch | git reset --hard <branch>@{1} |
Restore another branch moved by --update-refs |
git branch -f <other> <other>@{1} |
| Undo a pushed commit | git revert <commit> |
| Commit a fix into an earlier commit | git commit --fixup=<commit>, then git rebase -i main |
| Rebase a stack of branches | git rebase -i --update-refs main |
| Compare two versions of a branch | git range-diff main <branch>@{1} <branch> |
| Which commits are not in a branch yet | git cherry -v <upstream> <branch> |
| Backport a commit | git cherry-pick -x <commit> |
| Second working directory | git worktree add ../repo-hotfix -b hotfix main |
| Review a Forgejo PR | git fetch origin pull/<n>/head:pr-<n> |
| Remove a worktree | git worktree remove ../repo-hotfix |
| Find when a string appeared | git log -S '<string>' |
| Find the commit that broke something | git bisect start <bad> <good>, git bisect run <script> |
| Sign a commit | git commit -S |
| Sign during a rebase | git rebase -S main |
| Show signature status | git log --format='%h %G? %s' |
| Signed release tag | git tag -s v1.0 -m "Release 1.0" |
Conclusion
None of the features in this article are new. Worktrees have been around for over a decade, cherry-pick and the reflog for even longer. They just never make it into the tutorials, which stop as soon as the first push succeeds.
What changed my daily work most was not any single command. It was understanding that commits are snapshots, branches are labels and almost nothing is lost. After that, worktrees replaced my stash juggling, fixup commits replaced my “fix typo” commits, and I stopped being afraid of rebasing because I knew how to get back. Signing is the last piece: once every commit I push carries a signature from a key that lives on a smartcard, a leaked token is no longer enough to put code in my name.
If you take only one thing from this article, make it git worktree add. The next time somebody asks for a quick review while you are in the middle of something, you will see why.
Further Reading
- Pro Git, the free book by Scott Chacon and Ben Straub, especially the chapters on rewriting history and Git internals
- git-worktree(1)
- git-cherry-pick(1)
- git-rebase(1), including
--autosquashand--update-refs - git-range-diff(1)
- git-bisect(1), including the exit codes for
bisect run - Signing in Git, the
gpg.*configuration reference - lazygit, including its keybinding reference
- oct-git from the OpenPGP Card project
- larvitz/openpgp-card on Fedora COPR
- security/openpgp-card-tools-git on FreshPorts
- Hardware Keys Without GnuPG: The Rust OpenPGP Card Stack
- Chezmoi and Git: Dotfiles Without Pretending Every Machine Is the Same
Comments
You can use your Mastodon or other ActivityPub account to comment on this article by replying to the associated post.
Search for the copied link on your Mastodon instance to reply.
Loading comments...