Skip to content

Undo uncommitted changes in the wrong branch

Aine Riordan edited this page Aug 21, 2023 · 1 revision

Scenario:

You had intended to make changes to the feature branch, but inadvertently edited files in the main branch. You noticed the error before committing.

git status displays uncommitted changes.

$ (main) git status
On branch main
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:   modules/platform/con-cluster-platform-ext-database.adoc
no changes added to commit (use "git add" and/or "git commit -a")

Use git stash to record the changes you made and restore main to a clean state.

$ (main) git stash
Saved working directory and index state WIP on main: 6dc91a0 Merge pull request #141 from cbudz/aap-396

$ (main) git status
On branch main
nothing to commit, working tree clean

$ (main)  git log --oneline -n 3
6dc91a0 (HEAD -> main, upstream/main) Merge pull request #141 from cbudz/aap-396
ac43ac6 exchange quay for registry.io
27c669c Merge pull request #139 from cbudz/repo-change

Checkout the feature branch and extract the changed files with git stash pop.

$ (main) git checkout feature
Switched to branch 'feature'

$ (feature) git status
On branch feature
nothing to commit, working tree clean

$ (feature)  git log --oneline -n 3
308300f (origin/feature) Add feature Installation guide
e255c2d Feature: Initial commit
d9aee5e Merge pull request #93 from samccann/rpm-install

$ (feature) git stash pop
Auto-merging downstream/modules/platform/con-cluster-platform-ext-database.adoc
On branch feature
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:   modules/platform/con-cluster-platform-ext-database.adoc

no changes added to commit (use "git add" and/or "git commit -a")
Dropped refs/stash@{0} (e0bccf83835ef91fc0ecec344997a92d57358dfd)

$ (feature) git status
On branch feature
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:   modules/platform/con-cluster-platform-ext-database.adoc

no changes added to commit (use "git add" and/or "git commit -a")

$ (feature) git add .

$ (feature) git commit -m "Fix typo in modules/platform/con-cluster-platform-ext-database.adoc heading"
[feature b0814ea] Fix typo in modules/platform/con-cluster-platform-ext-database.adoc heading
 1 file changed, 1 insertion(+), 1 deletion(-)
Clone this wiki locally