Rowandish
Rowandish

Reputation: 2735

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

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.

Upvotes: 3

Views: 78

Answers (1)

user4046031
user4046031

Reputation:

If you want only to avoid manually deleting files then you can create git-command-name file

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

Put it into user/bin and git will recognised it as git command that you can call with

git command-name [path/to/the/folder]

Upvotes: 1

Related Questions