git restore

With git it seems you can always learn new hacks.

Today, a colleague of mine asked me if I know a quick way to restore a deleted folder from a past commit.

Version control xkcd strip

My first thought was the naive solution:
checkout a specific commit containing the directory, copy it to /tmp, return HEAD to your working branch and copy the folder to it.

way too naive, I know…

Then, another colleague suggested I’ll take a look at git checkout command documentation, and it delivered!

Solution

To restore a folder or a file from a specific commit:
git checkout <commit SHA> -- <file|foldername>

Example:

$ git checkout 797d624 -- deleted_folder

Salvage xkcd strip

Note: This can be also used to pick a file from a change not yet merged (commit in a PR), for review and testing.

comments powered by Disqus