2

Consider the following series of commands:

git init .
echo "Hello world" > Foo.txt
git add Foo.txt
git commit -m 'First commit'
echo Goobye > Bar.txt
git add Bar.txt
git commit -m 'Second commit'
git log
# Output:
commit 94fcd274a0d6c5c603e1a4eb3f7492989ccbca2a (HEAD -> main)
Author: <redacted>
Date:   Wed Oct 26 13:39:23 2022 -0700

    Second commit

commit 6317cf761676ed46c3cb20eeeb5a8dbd4a7fdfda
Author: <redacted>
Date:   Wed Oct 26 13:39:00 2022 -0700

    First commit


git checkout 6317cf761676ed46c3cb20eeeb5a8dbd4a7fdfda -- .
git diff 6317cf761676ed46c3cb20eeeb5a8dbd4a7fdfda

The output of the final command:

diff --git a/Bar.txt b/Bar.txt
new file mode 100644
index 0000000..b079804
--- /dev/null
+++ b/Bar.txt
@@ -0,0 +1 @@
+Goobye

The behavior I expected was that the output would be empty.

I expected the state of the working tree to be exactly equivalent to commit 6317cf761676ed46c3cb20eeeb5a8dbd4a7fdfda after running git checkout 6317cf761676ed46c3cb20eeeb5a8dbd4a7fdfda -- ..

However, it seems like git checkout <sha> -- . does not remove newly added files.

Is there a variation of the git checkout <sha> -- . command that does cause the working tree to exactly match the state of the old commit, without actually moving the current branch?

merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • 2
    `git checkout --no-overlay -- .` [The docs](https://git-scm.com/docs/git-checkout#Documentation/git-checkout.txt---overlay). Found in https://stackoverflow.com/a/55083251/7976758 , https://stackoverflow.com/search?q=%5Bgit-checkout%5D+delete+file – phd Oct 26 '22 at 20:54
  • 1
    Thanks! I looked for 'delete" in the docs and didn't see it. Didn't know the term "overlay". Happy to close as dupe or accept this as an answer. – merlin2011 Oct 27 '22 at 00:09
  • 1
    Consider also `git restore`, which is like this kind of `git checkout` *and* **defaults** to `--no-overlay` (and has `--overlay` to switch to the checkout-style behavior). – torek Oct 27 '22 at 05:08

0 Answers0