Alice
Alice

Reputation: 1400

Reset to a single file but back with the current contents unchanged

I mistakenly delete lots of previous content from current working file foo. md,

then need go back to the head of the single file's status of yesterday and copy that contents then switch to the current head and paste it.

Refer to the answer git - Hard reset of a single file - Stack Overflow

  git checkout HEAD -- my-file.txt

it will jump to its state in the index with that from HEAD but side effect to erase the modifications of today.

How could reset to the status of yesterday and back to the current with the file unchanged?

Upvotes: 2

Views: 65

Answers (3)

Simson
Simson

Reputation: 3559

Sometimes when one make this kind of mistakes just to bring up a side by side comparison of both versions is the easiest way to find and restore the removed lines.

There is another useful git command for this:git difftool. It will launch your favourite difftool (something like meld orbeyond compare) you will be able to compare the contents of current foo.md and the previous version.

git difftool HEAD~ foo.md

also

git difftool --dir-diff HEAD~

is useful when comparing all files at the same time.

Upvotes: 0

Romain Valeri
Romain Valeri

Reputation: 21938

Commit the file on a temporary branch

# create the temp branch
git checkout -b temp

# make sure the index is empty of changes
git reset

# Add and commit your file
git add my-file.txt
git commit -m "temp commit"

Then you'll be able to go back to your branch and switch freely between both states :

git checkout your-branch

# then to switch between states
git checkout temp -- my-file.txt
git checkout HEAD -- my-file.txt

Upvotes: 3

Tobias
Tobias

Reputation: 2575

If you want to checkout a file from HEAD it seems that you have not already committed it. So the easiest way would be to use git stash:

git stash

Now the changes are saved in a stack and everything is like in HEAD (except new created files I think)

Now if you want to go back to what you changed use stash pop:

git stash pop

This will pop the last stashed changes from the stack and your changes you've done today are back in the working directory.

Upvotes: 1

Related Questions