Sub topic 4
Choosing the commit to reset to
This chapter assumes you can run git log, git status, and git commit, and that you know a branch is a movable name for a commit. You should also know that HEAD normally points at your current branch. The later chapters cover what each reset mode does to the index and working directory. This chapter covers the argument you give git reset: which commit it moves to.
The shape of the command
git reset [--soft | --mixed | --hard] [<commit>]<commit> is any expression Git can resolve to a commit. If you leave it out, Git uses HEAD. Before the reset moves anything, Git turns your expression into one full commit hash. The branch then points at that hash.
So choosing a target is a question of naming a commit precisely. A wrong name does not produce an error. It produces a valid reset to a commit you did not mean.
Set up a practice repository
Create the three-commit repository used throughout this tutorial:
git init demo && cd demo
echo one > file.txt
git add file.txt
git commit -m "first"
echo two >> file.txt
git commit -am "second"
echo three >> file.txt
git commit -am "third"
git log --onelineThe log shows three lines, newest first. Your hashes will differ from anyone else's, because a hash is computed from the commit's content, author, and timestamps.
Relative names: HEAD~n and HEAD^
Commits form a chain in which each commit records its parent. Relative names count steps along that chain.
You can check what a name resolves to without changing anything. git rev-parse prints the hash, and --short abbreviates it:
git rev-parse --short HEAD
git rev-parse --short HEAD~1
git rev-parse --short HEAD~2
git rev-parse --short HEAD^
git rev-parse --short HEAD~~HEAD~1, HEAD^, and HEAD~~ shown above resolve as follows: HEAD~1 and HEAD^ give the same commit, and HEAD~~ gives the same commit as HEAD~2.
Tilde and caret differ on merge commits
On a linear history the two operators look interchangeable. They differ when a commit has more than one parent, as merge commits do.
~nfollows the first parentntimes.HEAD~3means "first parent of first parent of first parent".^nselects the nth parent of one commit.HEAD^2is the second parent ofHEAD.HEAD^is shorthand forHEAD^1.
The first parent of a merge is the branch you were on when you ran git merge. The second parent is the tip of the branch you merged in. You can combine the operators: HEAD~2^2 means "go back two first-parent steps, then take the second parent of that commit".
The rule HEAD~1 equals HEAD^1 always holds. Resetting to HEAD~1 after a merge therefore removes the merge commit and leaves you on the first-parent side, at the commit you were on before merging.
Absolute names: hashes, branches, and tags
Relative names depend on where HEAD is now. Absolute names do not.
| Expression | Resolves to | Typical use |
|---|---|---|
| `a1b2c3d` | The commit with that abbreviated hash | Return to a commit you found in `git log` |
| `main` | The tip of branch `main` | Make your branch match another local branch |
| `origin/main` | Your last-fetched copy of the remote branch | Discard local commits and match the remote |
| `v1.2.0` | The commit a tag points to | Return to a released state |
| `HEAD@{2}` | Where `HEAD` pointed two moves ago | Undo a reset or other move (see the reflog chapter) |
| `main@{yesterday}` | Where `main` pointed yesterday on this machine | Return to a recent known-good state |
| `:/typo` | The newest commit whose message matches "typo" | Jump to a commit by message |
A few details matter here.
- Abbreviated hashes need enough characters to be unique in the repository. Git refuses an ambiguous prefix with an error rather than guessing. Four characters is the minimum, and seven or eight is usual.
- Annotated tags point to a tag object, not directly to a commit. Git follows the tag to the commit it names, so
git reset --hard v1.2.0works for both lightweight and annotated tags. origin/mainis a snapshot from your lastgit fetch. If you have not fetched recently, it is stale. Rungit fetchfirst so you reset to the remote's current state.- Reflog expressions such as
HEAD@{1}count moves in your local reflog, not ancestors.HEAD@{1}can be a commit that is not an ancestor ofHEADat all.main@{1}andHEAD@{1}are different things, because each ref has its own log. :/textsearches messages of commits reachable from any ref, and the text is a regular expression. It returns the most recent match, which may not be the commit you were thinking of. Check it before you reset.
The target does not have to be an ancestor
Most resets go backward, to an ancestor of HEAD. Git does not require that. If you run git reset --hard other-branch while on feature, then feature points at the same commit as other-branch. Any commits that were on feature and not reachable from another ref stop being reachable from any branch name. They are not deleted at once, because the reflog still references them, but ordinary git log no longer shows them.
This is the reason to check a target before running a reset. A reset to an unrelated commit is accepted without complaint.
Preview a target before you commit to it
A safe habit is to resolve and inspect the name first. Each of these commands is read-only:
git rev-parse --short HEAD~2
git log --oneline -1 HEAD~2
git log --oneline HEAD~2..HEAD
git diff --stat HEAD~2git log --oneline -1 <target>prints the single commit you would land on.git log --oneline <target>..HEADlists the commits that would leave the branch. If the list is longer than you expected, your target is wrong.git diff --stat <target>shows which files differ between the target and your working directory. That is roughly the amount of change a--hardreset would affect.
After you have checked the target, run the reset. A --soft reset is the cautious choice for a first attempt, because it never touches your files:
git reset --soft HEAD~2
git log --oneline
git statusThe log now shows only first. Status shows the changes from second and third as staged. Nothing was lost, and you can return to where you started:
git reset --soft ORIG_HEAD
git log --onelineORIG_HEAD is where HEAD pointed before the reset. The log shows all three commits again.
Limits of relative names
You cannot count past the first commit. In the demo repository, HEAD~2 is the root commit, so HEAD~3 has nothing to resolve to:
git rev-parse HEAD~3Git prints an error such as unknown revision or path not in the working tree and exits with a non-zero status. A failed name resolution aborts git reset before it changes anything. A name that resolves to the wrong commit is the dangerous case, so a failure is the safer outcome.
There is also no commit "before" the root, so you cannot reset a branch to an empty history with git reset. Starting over from nothing needs a different approach, such as creating a new orphan branch.
Paths and commits in the same command
git reset also accepts file paths, which a later chapter covers. For choosing a target, only the parsing rule matters. When arguments could be either a commit or a path, Git decides by checking whether each one is a valid revision or an existing file. If a name could be both, for example a branch called docs and a directory called docs, Git stops with an "ambiguous argument" error. Put -- before the paths to say which is which:
git reset HEAD~1 -- docs
git reset -- docsIn the first command, HEAD~1 is the commit and docs is the path. In the second, no commit is given, so the default of HEAD applies and docs is a path. Using -- whenever you pass paths avoids guessing.
Shell quoting problems
Some target expressions contain characters that your shell treats specially. If a command behaves oddly, quote the expression.
- In PowerShell, braces and
@have special meanings, so writegit reset --hard "HEAD@{1}". - In zsh with the
extended_globoption on,^can act as a pattern operator. Write'HEAD^'or useHEAD~1. - In Windows cmd.exe,
^is the escape character, so you need to double it (HEAD^^) or useHEAD~1.
HEAD~1 is the form least likely to be altered by any of these shells, and it is the one this tutorial uses.
Summary of choices
- To remove the last commit, use
HEAD~1. - To remove the last
ncommits, useHEAD~n. - To go to a specific known commit, use its hash from
git log. - To match another branch or the remote, use its name, and fetch first for remote branches.
- To undo an earlier move, use a reflog expression such as
HEAD@{1}orORIG_HEAD. - For merge commits, use
~for the first-parent line and^2to reach the merged-in side.
Exercise
A merge commit M has two parents: A, the branch you were on when merging, and B, the tip of the merged-in branch. Which expression resets the branch to A, and which names B? Why is HEAD~1 a safe way to undo the merge?
Show answer
HEAD^1, which is the same as HEAD^ and HEAD~1, names A. HEAD^2 names B. ~ follows the first parent, so HEAD~1 resolves to A, the commit you were on before the merge. Resetting to it removes the merge commit and keeps the branch on its original line.
Exercise
You run git reset --hard origin/main right after a colleague says they pushed a fix, but your local origin/main does not contain it. What went wrong, and what should you have run first?
Show answer
origin/main is your last-fetched copy of the remote branch, not the live remote. The reset moved your branch to the stale copy. You should have run git fetch first so that origin/main pointed at the remote's current commit. Afterward, git log --oneline origin/main..HEAD would also have shown which local commits were about to leave the branch.
Exercise
In a repository with exactly three linear commits, what happens when you run git reset --soft HEAD~3, and what does git rev-parse HEAD~3 print?
Show answer
HEAD~3 would be the parent of the root commit, which does not exist. git rev-parse HEAD~3 prints an "unknown revision" error and exits non-zero, and git reset --soft HEAD~3 fails the same way without changing anything. The furthest back you can reset in this repository is HEAD~2.