A Git commit isn’t a set of diffs, a branch is a 41-byte file holding a SHA hash, and
amendandrebasenever edit old records—they create brand-new objects with different hashes.
Most Git mistakes happen when you think of it as a folder of backups or a linear stack of patches. That mental model gets you through add, commit, and push, right up until a rebase conflict, an accidental reset --hard, or a botched merge undo turns into lost work and a broken shared branch. In this guide, we’ll unpack the object model inside .git, the staging area (index), branches and HEAD, merge and rebase strategies, syncing with origin, and recovering lost work through the reflog.
Mental Model: Three Areas, Objects, and Pointers
| How it looks from the CLI | What Git actually does |
|---|---|
| Git only stores diffs between versions | Each commit points to a full directory snapshot (tree) and its ancestor (parent) |
git add just marks a file for upload |
It writes the file’s contents (blob) into .git/objects and updates the index |
| A branch is a separate copy of the folder | A branch is a movable file holding the hash of one commit in a directed graph |
amend and rebase edit old commits |
They create brand-new objects with new hashes; the old ones remain reachable via reflog |
git reset --hard erases commits forever |
Only the branch pointer moves; the objects stay in the database until garbage collection |
Every change flows through three areas, and Git’s history commands differ solely by which of these areas they touch (git add and git commit are covered in the next sections, while git restore, git reset, and git reflog are broken down in Undoing Changes, stash, and Recovery with reflog):
Inside .git and Basic Configuration
To see how branches and commits work without any hand-waving, let’s inspect .git directly after making two commits to a text file called app.txt:
$ cat .git/HEAD
ref: refs/heads/main
$ cat .git/refs/heads/main
71f547bd5d10351a7ede30db35c903786bb5ea89
$ git cat-file -p HEAD
tree 9f323068d689290e9eaf947e33f26e84485db144
parent 7f18f0042cbe3ed692ccab8c0ab442473a990fae
author Alice <[email protected]> 1796059225 +0300
committer Alice <[email protected]> 1796059225 +0300
update line 10
$ git cat-file -p 'HEAD^{tree}'
100644 blob 8e304b423d41563856ace1815d4ba8c126b29a5a app.txt.git/HEADdoesn’t hold a hash—it holds the name of the active branch:ref: refs/heads/main.- The branch file
.git/refs/heads/mainstores a single commit SHA hash:71f547bd.... - Inside the commit object itself are a pointer to the root
tree, a pointer to the previous commit (parent), two metadata lines (authorandcommitter), and the commit message. - The
treeobject lists file permissions, object type (blob), content hash, and filename for every tracked file. git cat-file -pprints a raw object from.git/objects, andHEAD^{tree}resolves to the file tree referenced byHEAD.
Initial Setup and Configuration
Without a name and email, Git refuses to create commits because author and committer are mandatory fields in every commit object. It’s also worth setting main as the default branch name and choosing your preferred editor for interactive operations (like rebasing or committing without -m).
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
git config --global init.defaultBranch maingit config --global core.editor "code --wait"git config --global core.editor "nano"git config --global core.editor "vim"Why main instead of master (and the AUR exception)
Historically, Git initialized repositories with a branch named master, though since 2020 GitHub, GitLab, and other hosting platforms switched their default to main. Without setting init.defaultBranch main, Git prints a multi-line hint on every git init suggesting you rename the branch—and pushing to a freshly created remote repository (if initialized with a README or license on the server) leaves you with two separate branches. Not every platform follows this convention, however: the Arch User Repository (AUR), for instance, still only accepts pushes to master. For those repositories, override the setting locally (git init -b master or git -c init.defaultBranch=master clone ...) without touching your global config.
The --wait flag for VS Code tells Git to pause until you save and close the editor tab before resuming the operation.
Scope: all repositories for your user account on this machine.
File: ~/.gitconfig (Unix/macOS) or C:\Users\<Username>\.gitconfig (Windows).
Command:
git config --global <key> <value>Scope: current repository only (overrides global settings).
File: .git/config inside the project directory.
Command:
git config --local <key> <value>
# or omit the flag — local scope is the default
git config <key> <value>To inspect all active settings along with the files they come from:
git config --list --show-originInitializing a new repository in the current directory creates .git (we’ll cover cloning an existing project or wiring up origin in Syncing with a Remote Repository (origin)):
git initInitialized empty Git repository in <directory_path>The Index, .gitignore, and Partial Staging
A .gitignore file at the repository root defines path patterns that git status and git add should skip.
# Specific file in any directory
secrets.txt
# Temp directory at any nesting level
temp/
# Build directory at the repository root only
/build/
# All files matching an extension
*.log
# Negation (won't work if the parent directory is already ignored)
*.jpg
!logo.jpg.gitignore only applies to untracked files. If a file is already in the index or an earlier commit, Git will keep tracking changes to it. To remove it from the index without deleting it from disk, run git rm --cached and record the removal in the next commit (covered in Committing Changes and Rebuilding HEAD):
git rm --cached <file> # unstage and untrack a single file
git rm -r --cached <directory> # untrack a directory recursivelyOne critical caveat for teams: the file stays on your disk, but the next commit records its deletion from the repository tree. When teammates run git pull, Git will delete that file from their disks—so give the team a heads-up before untracking local configs like .env (or keep a .env.example template in the repo).
Staging Changes: git status, git add, and git add -p
git status splits the working directory into three buckets—staged changes ready to commit, modified tracked files, and new untracked files. For example, with a newly staged notes.txt, a modified tracked app.txt, and an untracked temp.log, the output looks like this:
$ git status
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: notes.txt
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: app.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
temp.logThe main ways to stage changes:
git add .— stages all changes and new files in the current directory and subdirectories (unlikegit add *, it catches dotfiles like.gitignoreas well as deletions).git add '**/*.js'— recursively stages files using Git’s own pathspec engine (single quotes prevent your shell from expanding**prematurely).git add {src,tests}/*.js docs/*.md README.md— combines shell brace expansion with explicit paths.git add -p <file>— interactively stages individual hunks when two unrelated tasks end up in the same file. Ifapp.txthas edits on lines 1 and 20, Git prompts you chunk by chunk:
$ git add -p app.txt
diff --git a/app.txt b/app.txt
index 8e304b4..5bd5f5c 100644
--- a/app.txt
+++ b/app.txt
@@ -1,4 +1,4 @@
-line 1
+line 1 modified
line 2
line 3
line 4
(1/2) Stage this hunk [y,n,q,a,d,k,K,j,J,g,/,e,p,P,?]?In this prompt, y stages only the current hunk, n skips it, s (split) breaks a large hunk into smaller pieces, and q quits.
Committing Changes and Rebuilding HEAD
git commit records the current state of the index as a new commit object:
git commit -m "feat: add authentication logic"
git commit -am "fix: correct calculations"The -a flag automatically stages modifications and deletions of already tracked files, but ignores new (untracked) files—those still need an explicit git add.
Conventional Commits
Using a <type>: <description> prefix makes history scannable without opening every diff and enables automated changelog generation.
| Type | Purpose | Example |
|---|---|---|
feat |
New feature | feat: add JWT validation |
fix |
Bug fix | fix: handle empty config file |
refactor |
Code restructuring with no behavior change | refactor: extract parser state |
docs |
Documentation changes | docs: update build flags |
style |
Formatting without logic changes | style: normalize indentation |
test |
Adding or updating tests | test: cover zero-length input |
chore |
Dependency updates and build config | chore: bump nasm version |
Commit descriptions follow the imperative mood, completing the sentence “If applied, this commit will… add email validation.”
Fixing the Last Commit (--amend) and the Two Timestamps
As long as the last commit hasn’t been pushed, you can rebuild it with --amend. Because this produces a new object with a different SHA hash (changing the tree, message, or committer date), using it on published commits breaks team sync (more on that in the origin section):
Stage the forgotten edits with git add, then rebuild the last commit while keeping its original message:
git commit --amend --no-editIf the file tree is already right, update just the commit message:
git commit --amend -m "feat: add email validation"Omitting -m opens your configured text editor.
As git cat-file -p HEAD showed earlier, every commit carries two timestamps: author (when the change was written) and committer (when the commit object was created). By default, --amend keeps the original author timestamp but updates the committer timestamp to now.
- Reset both timestamps to the current time:
git commit --amend --no-edit --reset-author- Freeze both original timestamps when amending the last commit:
GIT_COMMITTER_DATE="$(git log -1 --format=%cd)" git commit --amend --no-editInspecting History: git diff, git log, and Patches
Before committing, it pays to inspect your exact line-by-line changes. git diff prints differences in unified diff format, split into independent hunks—here is app.txt with edits near the top and bottom:
$ git diff app.txt
diff --git a/app.txt b/app.txt
index 8e304b4..5bd5f5c 100644
--- a/app.txt
+++ b/app.txt
@@ -1,4 +1,4 @@
-line 1
+line 1 modified
line 2
line 3
line 4
@@ -17,4 +17,4 @@ line 16
line 17
line 18
line 19
-line 20
+line 20 modifiedThe header @@ -17,4 +17,4 @@ means: in the old version, 4 lines are shown starting at line 17 (-17,4), and in the new version, 4 lines starting at line 17 (+17,4). Lines prefixed with - and + mark deletions and additions, while unprefixed lines provide surrounding context.
| Command | What it compares |
|---|---|
git diff |
Working directory against the index (unstaged changes) |
git diff --staged |
Index against HEAD (what the next commit will record; alias --cached) |
git diff <branch1> <branch2> |
Tips of two branches |
git diff <hash1> <hash2> |
Any two commits |
git diff --stat |
Summary of changed files and line counts only |
Reading History and Tracking Down Bugs
git log --graph --oneline --all --decorate— compact ASCII graph of all branches and pointers.git log --max-parents=0— find the root (initial) commit(s) in the repository.git log --format="%ad | %an: %s" --date=short— clean table showing date, author, and subject.git log -S "<pattern>"— find commits that changed the number of occurrences of a string (use-G "<regex>"to search diff lines by regular expression instead).git blame <file>— show the author and commit hash that last touched each line of a file.git bisect start/git bisect bad/git bisect good <hash>— binary search for the first broken commit. At each step, Git checks out the midpoint indetached HEADmode and halves the range based on yourgoodorbadverdict, pinpointing the culprit in checks; rungit bisect resetwhen done to return to your branch.
Creating and Applying Patches (git diff and git format-patch)
Git has no git patch command—patches are built on top of git diff. Which tool you reach for depends on whether you’re sharing raw file edits or full commits with metadata:
| Goal | Generate patch | Apply patch | What gets transferred |
|---|---|---|---|
| Share uncommitted edits or branch diffs | git diff > changes.patch |
git apply changes.patch |
File edits into the working directory (no commit) |
| Share finished commits with author and message | git format-patch main |
git am *.patch |
Full commits appended to the current branch |
Before applying a raw patch, you can dry-run it for conflicts without touching any files, or pass --staged to export staged edits:
git diff --staged > fix.patch # save staged changes to a patch file
git apply --check fix.patch # check whether the patch applies cleanly
git apply fix.patch # apply edits to the working directory
git format-patch -1 HEAD # export the last commit as 0001-*.patch
git am 0001-*.patch # apply the patch as a new commit preserving authorshipBranches, Merging, and Rebasing
Switching branches updates HEAD and the working directory in place without duplicating the repo:
git branch # list local branches (* marks the active one)
git branch <new-branch> # create a branch without switching to it
git switch <branch> # switch to an existing branch
git switch -c <new-branch> # create a branch and switch to it immediately
git switch --detach HEAD~2 # inspect an older commit in detached HEAD modeChecking out a specific commit hash or relative ref instead of a branch name puts the repository into detached HEAD.
Three Merge Scenarios (git merge)

| Scenario | When it happens | What happens in the graph | Trade-offs |
|---|---|---|---|
| Fast-forward | The target branch (main) has no new commits |
main simply slides forward to the feature branch tip |
Linear history with no extra commits; loses branch boundaries |
| Three-way merge | Both branches gained commits after diverging | Git finds the common ancestor, compares both tips against it, and creates a merge commit | Captures parallel work accurately; overlapping edits can conflict |
Empty merge (--no-ff) |
main hasn’t moved, but fast-forwarding is disabled |
Forces a two-parent merge commit even with zero new changes on main |
Clear feature boundaries in the graph; easy to revert the whole feature via revert -m 1 |
Why three-way merge needs three points instead of two: looking only at tips A and B, Git has no way to tell which branch changed a line and which left it alone. So it locates their nearest common ancestor (O) and compares both trees to it: if O had X, A still has X, and B has Y, then only B touched the line and Git takes Y cleanly. A conflict only occurs when both A and B modified the same line differently relative to O.
(We’ll look at undoing a merge with revert -m 1 and the trap hidden inside it in Undoing Changes, stash, and Recovery with reflog.)
You can spot the difference right away in a real commit graph. Below, feat/auth was merged into main with --no-ff (producing the loop and merge commit 4d6132f), whereas feat/fast was merged via fast-forward (8895857, with both branches pointing to the same commit):
$ git log --graph --oneline --all --decorate
* 8895857 (HEAD -> main, feat/fast) feat: fast change
* 4d6132f Merge branch 'feat/auth'
|\
| * 8f94a97 (feat/auth) wip: temp debug
| * aa271b8 fix: typo
| * 8ad7eb4 feat: add login form
|/
* ed18bb3 chore: initial commitOnce merged, delete finished feature branches locally and on the remote so stale pointers don’t pile up:
git branch -d <branch> # safe delete (refuses if the branch isn't merged yet)
git branch -D <branch> # force delete, discarding unmerged commits
git push origin --delete <branch> # delete the branch on the remote(We’ll cover git push and origin in the next section, and recovering an accidentally deleted branch from git reflog in the undo and recovery section.)
Rebasing (git rebase and git rebase -i)
git rebase takes the local commits on your current branch and replays them one by one on top of a new base. History stays linear, but every replayed commit gets a new SHA hash.
Interactive mode (git rebase -i HEAD~3) opens an editor listing the last three commits from oldest at the top to newest at the bottom (the reverse of git log). For the three commits in feat/auth, the todo list looks like this:
pick 8ad7eb4 # feat: add login form
pick aa271b8 # fix: typo
pick 8f94a97 # wip: temp debug
# Rebase ed18bb3..8f94a97 onto ed18bb3 (3 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
# commit's log message, unless -C is used, in which case
# keep only this commit's message; -c is same as -C but
# opens the editor
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit| Action | Effect |
|---|---|
pick |
Keep the commit as-is |
reword |
Keep the file tree, edit the commit message |
squash |
Fold into the previous commit and edit the combined message |
fixup |
Fold changes into the previous commit and discard this commit’s message |
edit |
Pause on this commit so you can modify files or amend it |
drop |
Remove the commit from the branch |
To rewrite an entire branch all the way back to the repository’s very first commit, run git rebase -i --root.
Conflict Anatomy and the ours/theirs Trap in rebase
A conflict happens when two branches make incompatible edits to the same lines of a file. During git rebase, Git pauses on the conflicting commit, writes conflict markers into the file, and leaves the repo in an in-progress rebase state. Suppose main sets port=9000 in config.txt while feat/port sets port=3000; running git rebase main produces:
$ git rebase main
Rebasing (1/1)
Auto-merging config.txt
CONFLICT (content): Merge conflict in config.txt
error: could not apply 03bff04... config: change port to 3000
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
$ cat config.txt
<<<<<<< HEAD
port=9000
=======
port=3000
>>>>>>> 03bff04 (config: change port to 3000)
$ git status
interactive rebase in progress; onto 424e641
Last command done (1 command done):
pick 03bff04 # config: change port to 3000
No commands remaining.
You are currently rebasing branch 'feat/port' on '424e641'.
(fix conflicts and then run "git rebase --continue")
(use "git rebase --skip" to skip this patch)
(use "git rebase --abort" to check out the original branch)
Unmerged paths:
(use "git restore --staged <file>..." to unstage)
(use "git add <file>..." to mark resolution)
both modified: config.txtLook closely at HEAD above: during git merge, <<<<<<< HEAD (--ours) is your branch, whereas during git rebase, Git first checks out the target branch (424e641) and replays your commits on top one by one. Because of that, HEAD (--ours) during a rebase is the target branch (port=9000 from main), and --theirs is your replayed commit (port=3000). Keep this flip in mind whenever you pick one side wholesale with git checkout --ours <file> / git checkout --theirs <file> (or pass -X ours / -X theirs to merge or rebase).
How to resolve a rebase conflict:
- Edit the conflicted file and remove all
<<<<<<<,=======, and>>>>>>>markers (or pick one side completely viagit checkout --ours/--theirs <file>). - Stage the resolved file:
git add <file>. - Resume without running
git commit: rungit rebase --continue(or cancel the whole rebase withgit rebase --abort). If several commits on your branch touch the same lines, Git may pause again on subsequent commits—just repeat these steps for each one.
Cherry-Picking Individual Commits (git cherry-pick)
When you need just one specific commit from another branch (such as an urgent hotfix) without merging the whole branch, use cherry-pick:
git cherry-pick <commit_hash> # apply the commit and create a new commit on the current branch
git cherry-pick -n <commit_hash> # apply the changes to the index only, without committingcherry-pick doesn’t link branches in the graph—it computes the diff of the target commit and creates a brand-new commit with a new SHA hash on your current branch (if it conflicts, resolve, git add, and run git cherry-pick --continue or --abort). Because it duplicates the change under a new hash, merging the original branch later can still trigger conflicts on those lines or leave duplicate-looking entries in the log.
Syncing with a Remote Repository (origin)
Connecting to a remote server usually starts either by cloning an existing repository or by attaching a remote URL to a local repository created with git init:
git clone <url> # download a repo with origin already configured
git remote -v # inspect configured remote URLs
git remote add origin <url> # attach a remote URL to a local repository
git push -u origin main # push the branch and link it to origin/mainThe -u (--set-upstream) flag links your local branch to its remote counterpart so subsequent git push and git pull commands need no arguments.
Locally, the remote server (aliased as origin by default) is represented by remote-tracking branches like origin/main:
git fetch origindownloads new objects and updatesorigin/mainwithout touching your localmainbranch or working directory. Adding-p(--prune) also cleans up local tracking refs for branches deleted on the server (git fetch -p).git pullrunsgit fetchfollowed bygit merge origin/main(creating an extra merge commit if histories diverged).git pull --rebaserunsgit fetchfollowed bygit rebase origin/main, replaying your unpublished local commits cleanly on top of your team’s changes.
When a teammate pushes a commit while you’ve made one locally, git fetch and git status report the divergence (for example, 4f1f850 landed on the server while you committed locally):
$ git fetch origin
From /tmp/git-guide-remote
9f800ae..4f1f850 main -> origin/main
$ git status
On branch main
Your branch and 'origin/main' have diverged,
and have 1 and 1 different commits each, respectively.
(use "git pull" if you want to integrate the remote branch with yours)Why You Shouldn’t Rewrite Published Commits (and How --force-with-lease Works)
If you amend or rebase commits that have already been pushed to origin, a normal git push fails with a non-fast-forward error—and if someone else pushed a commit to that branch that your local origin/feat/auth doesn’t know about yet, Git says fetch first:
$ git push origin feat/auth
To /tmp/git-guide-remote.git
! [rejected] feat/auth -> feat/auth (fetch first)
error: failed to push some refs to '/tmp/git-guide-remote.git'Never rewrite history on shared branches like main or dev. If you’ve rebased your own feature branch (say, feat/auth) before review, use --force-with-lease instead of a blind --force. It sends the hash of your local tracking branch (origin/feat/auth) as a precondition: “overwrite only if the remote branch hasn’t moved since I last checked.” In the example below, Alice’s local feat/auth points to 9fe4974 after an amend, her origin/feat/auth still points to c6f4bbe, and Bob has already pushed 7ec45ab. The server catches the mismatch, rejects the push with stale info, and saves Bob’s work.
Watch out for this trap: if you hit stale info, run git fetch, and immediately retry --force-with-lease, you’ll update your local “lease” (origin/feat/auth) and overwrite Bob’s commit anyway. The right move after a rejection is to fetch, inspect the incoming commits, and rebase onto them:
$ git push --force-with-lease origin feat/auth
To /tmp/git-guide-remote.git
! [rejected] feat/auth -> feat/auth (stale info)
error: failed to push some refs to '/tmp/git-guide-remote.git'
$ git fetch origin
From /tmp/git-guide-remote
c6f4bbe..7ec45ab feat/auth -> origin/feat/auth
$ git log --oneline ..origin/feat/auth
7ec45ab fix: edge case by Bob
c6f4bbe feat: add auth
$ git rebase origin/feat/auth
Rebasing (1/1)
Successfully rebased and updated refs/heads/feat/auth.
$ git push --force-with-lease origin feat/auth
To /tmp/git-guide-remote.git
7ec45ab..a83e465 feat/auth -> feat/authNotice that git log ..origin/feat/auth lists both Bob’s commit and the base c6f4bbe: after Alice’s amend, the old commit is no longer part of her local history, so ..origin/feat/auth shows every commit missing from her current HEAD.
After the rebase, Alice’s amended commit gets a new hash (9fe4974 → a83e465), and the push succeeds as a clean fast-forward 7ec45ab..a83e465 with Bob’s 7ec45ab intact (feat: add auth appears twice in the log because c6f4bbe was the original commit on the server and a83e465 carries the extra changes replayed from --amend --no-edit). git log --oneline -n 4 confirms it:
$ git log --oneline -n 4
a83e465 feat: add auth
7ec45ab fix: edge case by Bob
c6f4bbe feat: add auth
cd8c21a chore: initial commitRelease Tags (git tag)
To pin a release with a permanent name (unlike branches, tags don’t move when new commits land), create an annotated tag (-a stores a full object in .git/objects with tagger, date, and message; omitting -a creates a lightweight tag—just a static ref in .git/refs/tags/ for local bookmarks) and push it explicitly:
git tag -a v1.0.0 -m "release 1.0.0" # tag the current HEAD
git push origin v1.0.0 # push a specific tag (or --tags for all tags)Undoing Changes, stash, and Recovery with reflog
Shelving Work Temporarily (git stash)
When your working tree and index have half-finished edits and you need to switch branches right away, tuck them onto the stash stack with a descriptive note:
$ git stash push -m "wip: partial auth"
Saved working directory and index state On main: wip: partial auth
$ git stash list
stash@{0}: On main: wip: partial authBy default, git stash push saves tracked files from the working directory and index (pass -u to include untracked files too). Restore the changes with git stash pop (apply and remove from the stack) or git stash apply (apply while keeping a copy on the stack). If git stash pop hits a conflict, Git keeps the entry on the stack—once you resolve the conflict manually, drop it with git stash drop.
Discarding Working Changes and Untracked Files (git restore, git clean)
git restore <file>— discard unstaged edits in the working directory, restoring the version from the index/HEAD.git restore --staged <file>— unstage a file back into the working directory without losing your edits on disk.
Like git reset --hard below, git restore only touches tracked files and leaves new untracked files alone. To purge build artifacts or leftover untracked files, use git clean:
git clean -nd # preview which untracked files and directories would be deleted (dry-run)
git clean -fd # permanently delete untracked files and directoriesMoving the Branch Pointer (git reset)
git reset moves the current branch pointer to a target commit (such as HEAD~1), while its flag controls which areas get reset alongside it:
git reset --soft HEAD~1Undoes the last commit, leaving all of its changes staged in the index and ready for a new git commit (handy for squashing recent local commits).
git reset --mixed HEAD~1Undoes the commit and clears the index, but leaves your edits intact on disk—letting you re-split them into cleaner commits with git add or git add -p.
git reset --hard HEAD~1Moves the branch backward and overwrites both the index and working tree with HEAD~1. Any uncommitted edits to tracked files are permanently lost.
Recovering “Deleted” Commits with git reflog
Even after git reset --hard HEAD~2 wipes the last two commits from git log, their objects are still sitting in .git/objects and their hashes are recorded in git reflog. Below, two commits disappear from the branch, yet 7ea7dbf is right there in the reflog so we can jump straight back to it:
$ git reset --hard HEAD~2
HEAD is now at 7d02d69 feat: commit one
$ git log --oneline
7d02d69 feat: commit one
e27cc97 chore: base
$ git reflog -n 6
7d02d69 HEAD@{0}: reset: moving to HEAD~2
7ea7dbf HEAD@{1}: commit: feat: commit three
215aca2 HEAD@{2}: commit: feat: commit two
7d02d69 HEAD@{3}: commit: feat: commit one
e27cc97 HEAD@{4}: reset: moving to HEAD
e27cc97 HEAD@{5}: commit (initial): chore: base
$ git reset --hard 7ea7dbf
HEAD is now at 7ea7dbf feat: commit three
$ git log --oneline
7ea7dbf feat: commit three
215aca2 feat: commit two
7d02d69 feat: commit one
e27cc97 chore: basereflog rescues you from a bad rebase, --amend, or git branch -D in the exact same way: locate the pre-disaster hash and point your branch back to it (or spin up a new branch with git switch -c rescue <hash>).
Safe Undo on Shared Branches (git revert) and the Re-Merge Trap
Once a bad commit is on the server, never erase it with reset—record a new inverse commit instead:
git revert <hash_of_bad_commit>| Criterion | git reset |
git revert |
|---|---|---|
| Mechanism | Moves the branch pointer backward | Creates a new inverse commit |
| Effect on history | Rewrites the branch | Appends forward (safe for teams) |
| When to use | Local commits before pushing | Public and shared branches |
| Data-loss risk | High with --hard (uncommitted edits lost) |
Minimal: prior snapshots stay intact |
To revert a merge commit, you have to tell Git which parent line to keep with -m. You can inspect parent order via git show <merge_hash> (Merge: <parent1> <parent2>): 1 is the branch you were on when merging (usually main), and 2 is the branch that was merged in. (Watch out: if someone mistakenly merged main into a feature branch and then fast-forwarded main onto it, those parent numbers flip!) Here is what happens after reverting a merge of feat/demo with revert -m 1 and later trying to merge that branch again:
$ git merge --no-ff feat/demo --no-edit
Merge made by the 'ort' strategy.
demo1.txt | 1 +
demo2.txt | 1 +
2 files changed, 2 insertions(+)
$ git revert -m 1 HEAD --no-edit
[main efbd171] Revert "Merge branch 'feat/demo'"
2 files changed, 2 deletions(-)
$ git merge --no-ff feat/demo --no-edit
Already up to date.That Already up to date. response is the classic revert -m 1 trap. In Git’s graph, the feature branch’s commits are already ancestors of main—it was the later revert commit efbd171 that deleted their files. If you fix up the branch and merge it again, only new commits made after the original merge will land in main; the earlier ones stay reverted. To bring the whole feature back, revert the revert commit itself: git revert efbd171.
Common Pitfalls & Fixes
-
“I added a file to
.gitignore, yet it still shows up ingit statusand commits.”
Symptom: changes to a secrets or log file keep appearing in diffs even after updating.gitignore.
Cause:.gitignoreaffects untracked files only; the file is already recorded in the index.
Fix: untrack it without deleting it from disk usinggit rm --cached <file>(or-r --cachedfor a folder) and commit the index change. -
“I messed up my last local commit—forgot a file or left debug code in.”
Symptom: the wrong file or a typo in the message is already inHEAD, before pushing.
Cause: the snapshot was already committed to the local branch.
Fix: for a quick fixup, stage the corrected file and rungit commit --amend --no-edit; to re-assemble the commit from scratch, step back withgit reset --soft HEAD~1, tweak your files, and commit again. -
“I merged into
main, broke the build, and already pushed.”
Symptom: a broken merge commit is now on a shared branch, andresetwould desync everyone else.
Cause: the merge is already part of the public graph onorigin.
Fix: undo it forward withgit revert -m 1 <merge_hash>, keeping in mind that re-introducing the feature later requires reverting the revert (git revert <revert_hash>). -
“A mistake slipped into a commit 5–10 steps back on my local branch.”
Symptom: the bad commit sits in the middle of an unpushed local chain.
Cause:--amendandresetonly operate relative toHEAD.
Fix: rungit rebase -i HEAD~10, changepicktoediton the target commit, fix the files, rungit add . && git commit --amend --no-edit, and finish withgit rebase --continue(if it’s already pushed to a shared branch, usegit revert <hash>instead). -
“I made a few commits in
detached HEADmode and don’t want to lose them when switching branches.”
Symptom:git statussaysHEAD detached at ..., and switching back tomainwould orphan the new commits.
Cause:HEADpoints directly to a commit hash rather than a branch name.
Fix: right where you are, anchor those commits to a new branch withgit switch -c rescue-work; if you’ve already switched away, grab the hash fromgit reflogand rungit switch -c rescue-work <hash>. -
“I ran
git reset --hardby mistake and wiped two good commits.”
Symptom:git logshows an older state and the latest commits are gone from the branch.
Cause: the branch pointer moved back, though the commit objects still live in.git/objects.
Fix: look up the last good hash ingit reflog -n 10and restore the branch withgit reset --hard <hash>(the only thing reflog can’t save is uncommitted work that was never staged or committed).
Hands-On Lab
Goal. Walk through a complete cycle in an isolated directory: untracking a file with git rm --cached, rebuilding a local commit with reset --soft, merging with --no-ff, and undoing a merge with revert -m 1.
Setup.
- Everything runs inside a temporary
/tmp/git-labdirectory on branchmain. - A log file is accidentally committed first, then untracked via
git rm --cachedand hidden with.gitignorewithout deleting it from disk. - On a feature branch, you create two commits, rebuild the second commit via
git reset --soft HEAD~1, and merge intomainwith--no-ff. - Finally, you undo the merge commit using
git revert -m 1 HEAD.
Verification criteria.
- After untracking the log file and adding the rule to
.gitignore, the log file remains on disk while disappearing fromgit status. git log --graph --oneline -n 6displays a clear feature-branch loop, a merge commit, and a revert commit on top.- At the end,
git statusreportsnothing to commit, working tree clean, and the file from the reverted branch is absent frommain’s working tree.
Step-by-step script and expected output
mkdir -p /tmp/git-lab && cd /tmp/git-lab
git init -b main
echo "# Lab demo" > README.md
echo "debug line" > debug.log
git add README.md debug.log
git commit -m "chore: initial import"
# Remove debug.log from the index (rm 'debug.log' means removing from the index, not from disk)
printf '*.log\n' > .gitignore
git add .gitignore
git rm --cached debug.log
git commit -m "chore: stop tracking logs"
# Feature branch and rebuilding the top local commit
git switch -c feat/demo
echo "<h1>demo</h1>" > demo.html
git add demo.html
git commit -m "feat: add demo page"
echo "<p>tweaks</p>" >> demo.html
git commit -am "wip: demo tweaks"
git reset --soft HEAD~1
git commit -m "feat: finish demo page"
# Explicit merge and safe revert
git switch main
git merge --no-ff feat/demo --no-edit
git revert -m 1 HEAD --no-edit
git log --graph --oneline -n 6
git statusActual graph and status output at the end of the run:
* cba3743 Revert "Merge branch 'feat/demo'"
* 4215dfc Merge branch 'feat/demo'
|\
| * 3381ec4 feat: finish demo page
| * df4ceb8 feat: add demo page
|/
* 4f9a822 chore: stop tracking logs
* 4344054 chore: initial import
On branch main
nothing to commit, working tree cleanKey Takeaways
- Git operates on objects (
blob,tree,commit), the staging index (.git/index), and text-file branch pointers (.git/refs/heads/), which is why branching runs in constant time without copying files. .gitignorefilters only untracked paths; files already in the index have to be removed withgit rm --cached.- Use
git add -pto split mixed tasks inside a single file,git log -Sandgit bisectto hunt down regressions, andgit diff+git applyorgit format-patch+git amto exchange changes without merging branches. - During a
git rebaseconflict,HEAD(--ours) refers to the target branch you are rebasing onto, while--theirsrefers to the commit being replayed. git reflogrecovers commits lost to a badreset --hard,amend,rebase, orbranch -Dfor as long as those objects remain in the local store.- Only
git revertis safe on published history (and afterrevert -m 1, re-merging the old branch won’t restore the reverted commits unless you revert the revert commit itself), while rewriting personal remote branches should always be guarded with--force-with-lease.
Fast-forward, Three-way, Empty merge) is adapted from Noah Bieler’s article Git Fu — Red Belt.