Disambiguation similar behaving git commands checkout -- and restore

Viewed 69

So for years I have been using a subset of git commands that served me well. But I need to know the difference and preferred use of two very similar behaving commands. So.

When I have edits in one or more files that are checked into the repository and I want to remove all those edits (edits have not been staged), I use the command:

git checkout -- <path>

But apparently there's a more modern alternative.

git restore --source=HEAD --staged --worktree <path>

Is git checkout -- <path> going to be deprecated at some point? What is the difference between the two?

1 Answers

The main difference in behavior between the two commands :

git restore --source={xxx} [--worktree] [--staged] -- <path>
# and
git checkout {xxx} -- <path>

is

  • git restore will delete files that are not present in {xxx},
  • git checkout will not touch these.

So git restore has the desired behavior "restore that file/that directory to its exact state in commit {xxx}", with more room for accidental deletion.

Depending on the options you use (--worktree and/or --staged), the deletion will happen on disk and/or in the index. There also is a --overlay option to prevent deletion (and basically behave like git checkout {xxx} -- <path>).


git checkout is so much part of git (so many scripts depend on its current behavior), it is IMHO extremely unlikely that it changes behavior in such a drastic way.

Related