git-only command to restore a directory to a commit state

时间:2016-10-20 13:03:42

标签: git restore git-checkout

I would like to restore a whole directory (recursively) from the history of my git repository (exactly like this question).

I know that the right git command is:

git checkout [tree-ish] -- path/to/the/folder

But I have a problem: to restore an existing directory to the state of a commit, the content of the directory should be deleted first. In other case, existing files that didn't exist in the old commit won't be removed. So, to obtain exactly what I want I have to do the following command:

rm -Rf path/to/the/folder
git checkout [tree-ish] -- path/to/the/folder/

(See this answer and comments).

I'd like to know if there is a git-only command to achieve the same behaviour of the two commands above, in order to avoid making a rm manually.

EDIT: I do not want to remove untracked files or clean after the checkout, I do not have them. I want to restore a folder exactly like it was some commit ago, removing added files, restoring removed files and so on.

1 个答案:

答案 0 :(得分:1)

如果您只想避免手动删除文件,则可以创建git-command-name文件

 #!/bin/bash
 # main, path as argument...
 rm -Rf path/to/the/folder 
 git checkout [tree-ish] -- path/to/t

将它放入user / bin并且git会将其识别为可以使用

调用的git命令
  

git命令名[path / to / the / folder]