2

I am using a script to automatically checkout the first commit of each month, for the last 12 months. Occasionally something strange happens and I am no longer allowed to checkout past commits. The error goes something like this:

error: Your local changes to the following files wold be overwritten by checkout:

db tests/framework.cpp

Please, commit your changes or stash them before you can switch branches. Aborting

This has happened many times (I am not editing any files, just checking them out). I usually just download a fresh copy of the repo from Github and start the process again and it works. But once it breaks I don't know how to fix it, and it keeps happening. Any thoughts?

Here is the iteration going on in my script, followed by the output of git status

for i in {12..1}

do

cd
cd git/mongodb/mongo

git checkout master                   
git checkout $(git rev-list --before "$(date -d "$(date +%Y-%m-01) -$i months 00:01" +%Y-%m)-01" -n 1 HEAD)
git checkout master

Git status:

On branch master

Changes not staged for commit:

        modified:    dbtests/framework.cpp

Untracked files:

       SHA1.txt
       SHA1.txt.
       file
       file.

no changes added to commit

Zoe
  • 23,712
  • 16
  • 99
  • 132
blaughli
  • 537
  • 5
  • 11
  • 25

2 Answers2

3

You can use the --force flag to make Git do the checkout anyway.

Alternatively, you could use git reset --hard instead to reset to the commits, rather than using checkout.

Amber
  • 446,318
  • 77
  • 595
  • 531
  • Thanks Amber. Are there any downsides to using `--force` and `git reset --hard` ? And if I use `git reset --hard`, will `git checkout master` return me to the master? – blaughli Oct 20 '11 at 23:30
  • `--force` was not recognized, but `git reset --hard` works. But I'm not sure how to return to the most current commit afterwards. Help? – blaughli Oct 20 '11 at 23:53
  • Using `git reset --hard` moves the branch pointer around if you're currently on a branch. If you don't want to modify the current branch, either check out a new one or use `git checkout -f`. If you already moved your pointer around, you can use the remote tracking ref (assuming it's up-to-date): `git reset --hard origin/master`. Failing that, you can use the reflog (`git reflog`) to find where your branch used to be pointing and reset to that. – Amber Oct 20 '11 at 23:53
  • Great, I've got it. Thank you for this very useful help. – blaughli Oct 21 '11 at 00:03
0

The 2019+ syntax would now be using the new git switch command (Git 2.23+)

git switch -f ...

The -f is an alias for the --discard-changes option:

Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.

This is used to throw away local changes.

VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283