0

I need to restore a folder I deleted in Git but I am having trouble doing it so I end up with the folder in the correct branch.

I have done:

git checkout commit_id -- /path/to/folder

This just puts the repo in a detached HEAD state and I am unsure how to get the files back to the master branch?

I also tried:

git checkout -b restore commit_id -- /path/to/folder

This created a new branch, but when I tried to merge that branch into master it said it was "Already up to date".

Running the below didn't work either as per the apparent duplicate question, this simply switched me to the other branch again:

git checkout myBranch -- /path/to/folder

Why is this so hard to do? What is the correct way?

Brett
  • 19,449
  • 54
  • 157
  • 290
  • Possible duplicate of [Git: copy all files in a directory from another branch](http://stackoverflow.com/questions/2668886/git-copy-all-files-in-a-directory-from-another-branch) – Kristján Mar 23 '16 at 06:44

1 Answers1

1

Your first try should work. A working example:

▸ git init
Initialized empty Git repository in /Users/***/Desktop/repo/.git/

▸ mkdir foo
▸ echo "foo" > foo/1
▸ git add foo
▸ git commit -m "file in foo"

▸ echo "bar" > 1
▸ git add .
▸ git commit -m "file"

▸ rm -rd foo
▸ git add foo
▸ git commit -m "removed foo"

▸ echo "foobar" >> 1
▸ git add .
▸ git commit -m "change"

The tree now looks like this:

* 95e470d (HEAD -> master) change
* e644860 removed foo
* 35e2e02 file
* 16fd6f0 file in foo

▸ git checkout HEAD~2 -- ./foo/

Results in:

▸ git status

    new file:   foo/1

I figure maybe the path put in is wrong. When I would do git checkout HEAD~2 -- foo, nothing happens. Try to use a relative path starting with ./.

Peter
  • 2,932
  • 1
  • 12
  • 9
  • That did it thanks. I was doing it as just the folder name, but once I added `./` to the start of the folder name like `git checkout commit_id -- ./folder_name` it worked. – Brett Mar 23 '16 at 10:45