I accidently added and comitted file in master
instead of mybranch
branch. Now even I switch to mybranch
I can't see it by doing git status
. How do make that file appear again for adding/committing and re-add in mybranch
?
-
Is the file created and added only in one commit? – blashser Aug 26 '15 at 07:21
3 Answers
You can rebase this commit in your mybranch
First, fix master
branch
git checkout master
git branch tmp // This creates a branch in the "wrong" commit
git reset --hard HEAD~1
You move your master
branch one commit back. You still have a temporal branch pointing to your commit.
Now, Move the commit to mybranch
branch
git checkout tmp
git rebase --onto mybranch master tmp
git checkout mybranch
git merge tmp
git branch -d tmp
The rebase command:
- The starting point: --onto mybranch
- From what commit: master
- to what commit: tmp
I recommend you to open some frontend to see what you are doing. I use gitk
gitk --all &

- 921
- 6
- 13
In the master branch use git rm dir1/dir2/file
. In the correct branch use git show master:dir1/dir2/file >dir1/dir2/file
and git add dir1/dir2/file
If you have updated the master branch after the wrong commit, of course you cannot use master
in the git show
command to get the files back. You can use git reflog
to find a suitable reference. If it happens to be HEAD@{2}
the command will be git show HEAD@{2}:dir1/dir2/file >dir1/dir2/file
(git will automatically recognize that it is the same file contents, so you don't have to be worried about double disk space consumption.)

- 2,236
- 1
- 15
- 21
-
`master` has already been `stashed` so it's clear. Issue is that all local changes got removed. – Volatil3 Aug 26 '15 at 05:51
-
Not sure I understand what you mean the by "master has been stashed". You wrote the wrong files had already been committed, so you can get them back by git show. I added more instructions in case you have updated your master branch since (e.g. to revert the commit or committed the file removal) – Uwe Geuder Aug 26 '15 at 06:03
-
Look, I wrote code and accidently added in `master`. Now I have created a branch and reset the `master` by running `git stash`, which removed files from master. The changed file are already in `mybranch` – Volatil3 Aug 26 '15 at 06:05
-
1Git reset and git stash are different commands. In the original question you wrote you committed the wrong files, in the last comment you mention only adding. Again, these are different commands. You should edit your question to write a clear and complete sequence of relevant commands you gave (E.g. 1.) add 2.) commit. 3.) reset 4.) checkout, ... whatever it was) and then describe what you still want to achieve. git show with a reference from the reflog should also be suitable after git reset. git show works also from the stash, e.g. gitk will display the reference or sha1 to use. – Uwe Geuder Aug 26 '15 at 06:19