Sub topic 11
Staying safe: shared branches and untracked files
This chapter assumes you know what --soft, --mixed, and --hard change, and that you can read git status and git log. It covers the situations where git reset causes real damage and the habits that prevent it. There are two main risks. Rewriting history that other people already have is one. Losing work that Git cannot bring back is the other.
Two kinds of risk
A reset can hurt you in two different ways.
- Lost work.
git reset --hardoverwrites tracked files in your working directory. Changes that were never committed have no copy in the history, so the reflog cannot restore them. - Rewritten history. A reset moves your branch pointer backward. If other people already have the commits you removed, your branch and theirs now disagree, and fixing that affects everyone.
The two risks need different precautions. The first is about your own machine. The second is about your team.
What can and cannot be recovered
The reflog records where HEAD and your branches pointed. It does not record the contents of your working directory. That difference decides what you can get back.
| Situation | Recoverable? | How |
|---|---|---|
| Committed work removed by `reset --hard` | Yes | `git reflog`, then reset to the old position |
| Committed work removed by any reset, right after running it | Yes | `git reset --hard ORIG_HEAD` |
| Staged changes (ran `git add`) discarded by `--hard` | Sometimes | The file contents may still exist as unreferenced objects. `git fsck --lost-found` lists them until garbage collection removes them |
| Unstaged edits to tracked files discarded by `--hard` | No | Git never stored them |
| Untracked files | Not touched by reset | They stay in the working directory |
The second row assumes you act before ORIG_HEAD is overwritten by another command that sets it, such as a merge or a rebase.
The takeaway is that committing is the only reliable way to make work recoverable. Even a throwaway commit protects you.
Untracked files and reset
An untracked file is one that Git has never been told to track. It is in neither the index nor the last commit. Reset only moves the branch and rewrites the index and tracked files, so it generally leaves untracked files alone.
You can check this in a small repository.
git init safety-demo && cd safety-demo
echo one > file.txt
git add file.txt
git commit -m "first"
echo two >> file.txt
git commit -am "second"
echo scratch > notes.txt
echo "unsaved edit" >> file.txt
git status --shortThe status shows two entries: M file.txt (modified, not staged) and ?? notes.txt (untracked). Now run the hard reset.
git reset --hard HEAD~1
git status --short
cat file.txtThe output now shows only ?? notes.txt, and file.txt contains just one. Two things happened to file.txt. The "second" commit was removed, and the unsaved edit disappeared. The edit was never committed or staged, so no copy exists. The untracked notes.txt survived.
This leads to a common misconception: that git reset --hard gives you a completely clean directory. It does not. Untracked files remain, which can be a surprise if a build leaves generated files behind.
There is one exception to "untracked files are safe". If the commit you reset to contains a file at the same path as an untracked file in your working directory, --hard can overwrite the untracked file without asking. Back up any such file first.
Removing untracked files with git clean
When you want a truly clean directory, the tool is git clean, not git reset. It deletes files permanently, and they were never in Git, so nothing can restore them. Always preview first.
git clean -nThe -n flag (dry run) lists what would be removed and deletes nothing. Once the list looks right, run the real thing.
git clean -fTwo options extend the reach.
-dalso removes untracked directories.-xalso removes files that.gitignorehides, such as build output, local configuration, and sometimes credentials files you kept out of Git on purpose.
A pre-reset checklist
Before any --hard reset, spend ten seconds on these checks.
- Run
git status. Anything listed under "Changes not staged for commit" will be lost. - Run
git diffandgit diff --stagedif you are unsure what those changes are. - Decide whether to keep them. If so, commit them or run
git stashfirst. - Create a marker for your current position, as shown below.
git branch backup/before-resetThis creates a new branch pointing at your current commit. It does not switch to it and changes nothing else. If the reset goes wrong, git reset --hard backup/before-reset returns you exactly. Unlike a reflog entry, a branch does not expire. Delete it once you are sure you no longer need it.
git branch -d backup/before-resetIf Git refuses with "not fully merged", that is a signal. The backup holds commits nothing else contains. Use -D only when you are certain you want to discard them.
Shared branches
Everything above affects only your machine. The second risk begins when commits leave it.
Git identifies a commit by a hash computed from its content and its parent. A reset does not change or delete commits. It moves your branch to point at an older one. The removed commits still exist, but your branch no longer includes them. If you had already pushed them, the remote branch still includes them, and your local branch is now behind in a way that looks like divergence.
git push origin feature/loginAfter a reset of pushed commits, this push is rejected as a non-fast-forward update. Git is telling you that the remote has commits yours does not contain.
Check before you reset
Find out whether the commits you plan to remove are already on a remote.
git fetch origin
git log --oneline origin/main..HEAD
git branch -r --contains HEAD~1The first command refreshes your view of the remote. The second lists commits on your current branch that origin/main does not have. Those are the unpushed ones, and removing them is safe. The third lists the remote branches that contain the commit before your latest one. If it prints anything, that commit has been published.
Replace main with the branch you compare against.
What happens if you force-push
You can make the remote match your reset branch by forcing the push. That throws away the commits on the remote, and teammates who already pulled them still have them. When they next pull, Git tries to merge their copy of the old commits with your rewritten branch. The old commits can come back, or conflicts can appear that look unrelated to anyone's recent work.
If you must overwrite a remote branch, use the safer form.
git push --force-with-lease origin feature/login--force-with-lease refuses to overwrite the remote if it has moved since you last fetched. That protects you from deleting a commit a teammate pushed a minute ago. Plain --force has no such check.
A teammate whose local branch is affected can realign with the rewritten remote, but only if they have no local commits to keep.
git fetch origin
git reset --hard origin/feature/loginAnyone with unpushed work on that branch should first save it, for example with the backup branch from the checklist.
Use revert for published commits
When the commits are already shared, undo them by adding a new commit that reverses their changes.
git revert HEADThis keeps history intact, so every teammate can pull the result normally. The chapter on reset versus revert versus restore compares the options in more detail.
The diagram summarizes how to choose.
Common errors
- Resetting the wrong branch. Run
git branch --show-currentbefore a reset. The reset acts on whichever branch is checked out. - Treating
ORIG_HEADas permanent. It is overwritten by the next operation that sets it. If you want a lasting marker, create a branch. - Waiting too long to use the reflog. Entries expire. By default, reachable entries last 90 days and unreachable ones 30 days, and
git gccan then remove the commits themselves. - Assuming reflog is shared. The reflog is local to each clone. A teammate cannot recover commits from your reflog, and you cannot recover from theirs.
- Running
git cleaninstead ofgit reset. The two commands remove different things. Reset handles tracked files and history. Clean handles untracked files.
Summary of safe habits
- Commit or stash before you reset. A committed change can always be recovered.
- Read
git statusbefore every--hard. - Make a backup branch when the reset is large or you are unsure.
- Check whether commits are published before you remove them.
- Prefer
git revertfor shared history, and--force-with-leaseif a force-push is truly needed. - Preview with
git clean -nbefore deleting untracked files.
Exercise
You run git reset --hard HEAD~2 in a repository that contains one untracked file, todo.txt, and an unstaged edit to the tracked file app.py. Which of these survives, and can the lost one be recovered with the reflog?
Show answer
todo.txt survives, because reset does not touch untracked files (unless the target commit has a file at that same path). The unstaged edit to app.py is overwritten. The reflog cannot recover it, because the edit was never committed, and the reflog records only where HEAD and branches pointed. The two removed commits can still be recovered with git reset --hard ORIG_HEAD.
Exercise
You reset a local branch back three commits, and git push is rejected. Two of the three commits were already pushed and a teammate has pulled them. What should you do, and why is plain git push --force a poor choice?
Show answer
Prefer git revert for the published commits. Restore the branch with git reset --hard ORIG_HEAD and revert the two pushed commits so history is only added to. If you must overwrite the remote, use git push --force-with-lease, which refuses if the remote has moved since your last fetch, and tell your teammate to realign with git fetch and git reset --hard origin/<branch> after saving any local work. Plain --force skips the check and can erase commits someone else pushed.