Home > Software design >  What's the difference between git restore and git checkout-index?
What's the difference between git restore and git checkout-index?

Time:10-12

There are two confusingly similar commands, git restore and git checkout-index. I see git restore checks out files into the worktree. I also see git checkout-index also checking out files into the worktree. Based on those answers, it sounds like both commands do the same thing. Both were seemingly introduced to clarify the multiple different usages of git checkout. Is the only difference the mere formality and API-stability i.e. the "porcelain" or "plumbing" nature of these two commands?

CodePudding user response:

The git restore command is used to unstage changes or in a way sync your current branch/source to a difference branch/source.

The git checkout-index command will copy all files listed from the index to the working directory (not overwriting existing files).

The primary difference is that with the restore command you can specify which things you want to sync with your current branch or worktree using the --worktree flag. Or sync the staged files using the --staged flag.
While in the checkout-index command all the files are copied from an index. Restoring is like copying from a backup and checkout is like adding files from your own index.

For more info, checkout the manpages of these commands: git restore: Here git checkout-index: Here

CodePudding user response:

One could say that git checkout-index still exists partly for historical reasons, but these commands have different features.

The main one is :

  • git restore has options which allow to restore from something other than the index (another commit, or a tree), and can update the index
  • git checkout-index will exclusively take content from the index to your disk, and will never change the index

Also, git checkout-index has a set of options which make it a good candidate to "take the content of a file in the index to run it through a linter" (typically in a pre-commit hook) :

  • by default, it will not overwrite an existing file (unless you add -f in the options, you know you will not remove changes from your disk)
  • it has the --prefix (for example: --prefix=/tmp/) or --temp options, to easily create temp copies of some files

git restore, on the other hand, was written with the intention to replace git checkout -- <filenames> - restore the version of a file :
when used with the --worktree option (which is on by default), it will overwrite and delete files from your disk

  • there is an option to avoid the "delete files" part (--overlay -- that's git clarity for you :) ),
  • there is currently no option to avoid the "overwrite files" part (if you run git restore --worktree, you probably want to overwrite something anyway ...)

(for completeness : the git checkout branch part - change active branch - is covered by git switch)

  •  Tags:  
  • git
  • Related