Restore a file without adding to the index using Git

29 Nov 2020 in TIL

After fetching a list of deleted files with --git-diff-filter I wanted to restore the files to my current working directory.

Historically I have used git checkout <committish> </path/to/file> to achieve this, but it had the unwanted side effect of adding the file to the index automatically, requiring a call to git reset </path/to/file> to unstage it.

Searching for a better option, I discovered that the recently added git restore command has a way to restore files too.

The command can also be used to restore the content in the index with --staged, or restore both the working tree and the index with --staged --worktree.

Splitting the behaviour in to --staged and --worktree allows us to restore files without adding them to the index by calling git restore with the --worktree flag only.

bash
git restore --source <committish> --worktree </path/to/file>

This will restore the file to the working directory without adding the file to the index.

Via https://git-scm.com/docs/git-restore