5

I need to update working directory and index to the state of some commit. When I run git checkout Git updates HEAD, index and a working directory. I know I can checkout a single file from a commit without updating HEAD by simply specifying a path to the file. But what is the best way to do that for the entire working directory?

At the moment I'm simply doing:

ID=$(git rev-parse HEAD)
git reset --hard COMMIT_ID
git reset --soft $ID
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

8

Use git checkout with a dot as a path

git checkout COMMIT_ID .

From the man page of git checkout:

git checkout [<tree-ish>] [--] <pathspec>…​

Overwrite paths in the working tree by replacing with the contents in the index or in the <tree-ish> (most often a commit). When a <tree-ish> is given, the paths that match the are updated both in the index and in the working tree.

The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using -f will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using --ours or --theirs. With -m, changes made to the working tree file can be discarded to re-create the original conflicted merge result.

torek
  • 448,244
  • 59
  • 642
  • 775
Ferrybig
  • 18,194
  • 6
  • 57
  • 79
  • 1
    It's more an operating specific feature, `.` means the current directory, and git uses it to calculate that since you have a command line open in the root of the git repository, git knows that you want to checkout all files from the specified "tree-ish" – Ferrybig Mar 30 '18 at 11:54