user3310334
user3310334

Reputation:

How to un-add file from last commit but keep local changes?

I edited two files. I wanted to commit both files separately. I accidentally did:

git add file_one
git commit -am 'Change something in file_one'

The -a flag committed my changes to file_two as well, which I didn't want.

How do I undo that?

What I was aiming for from the start was:

git add file_one
git commit -m 'Change something in file_one'
git add file_two
git commit -m 'Change file_two'

I tried

git reset --soft HEAD^ -- file_two

but soft reset doesn't work with paths apparently, and I also tried (rip)

git checkout HEAD~ -- file_two
git commit --amend

but now I just completely deleted all changes in file_two.... annoyingly. I'm asking the question so I don't make such a mistake again.

Upvotes: 2

Views: 345

Answers (3)

Enlico
Enlico

Reputation: 28500

Edit

This answer was posted before this other answer was fixed. At the moment I think that one is better than mine, technically speaking.

Original answer

The OP had a repo going on very well

mkdir testdir
cd testdir/
git init
echo 'historical content of file_one' > file_one
echo 'historical content of file_two' > file_two
git add file_one file_two
git commit -m 'this is the most recent commit the OP is happy with'

Then the OP started editing both files, with the intention of committing them in two separate commits,

echo 'one more line to file_one' >> file_one
echo 'one more line to file_two' >> file_two

however the OP made a mistake, commmitting both files:

git commit -am 'this commit was meant to be only for file_one'

At this point, I would do the following:

git reset HEAD~

which essentially goes back to before git add file_one file_two, and then I'd stage file_one and commit it using the old message, and then stage file_two and commit it too:

git add file_one
git commit --reuse-message=HEAD@{1}
git add file_two
git commit -m 'Committing only changes to file_two

Upvotes: 2

Calum Halpin
Calum Halpin

Reputation: 2105

EDIT: I initially misunderstood the question so this answer intially suggested deleting file_2 from the staging tree. As Enrico pointed out in the comments, that isn't what you want if file_2 isn't new.

You can restore the staged version of file_2 to its pre-commit state with:

git reset HEAD^ -- file_two

You want a mixed reset because you want to affect the staging tree.

Then you can amend your last commit with:

git commit --amend

Your working tree will be unaffected.

Upvotes: 4

src3369
src3369

Reputation: 2039

You can just undo last commit and then you can commit both files separately in 2 different commits. You needed to just soft/hard reset to remove the entire last commit from git
hard reset - git reset --hard HEAD^ - doesn't preserve the undone changes
soft reset - git reset --soft HEAD^ - does preserves the undone changes locally

Upvotes: 0

Related Questions