Undo git mv (rename)

84.7k Views Asked by At

What is the right way to undo a rename in git, like:

git mv file1 file2
10

There are 10 best solutions below

5
CanSpice On BEST ANSWER

Non-cheeky answer:

git mv file2 file1

Updates the index for both old and new paths automatically.

Check documentation of git mv

1
William Pursell On

It depends on what you want to accomplish. If you want it to appear as if the file was never moved, then you can reset (or rebase) back to before the move. If you don't care about the history, then just move it back.

0
Dave Konopka On

If you've accidentally renamed a large number of files and want to get back to where you started, delete all the renamed files that show up as adds under a git status call.

Once you delete all the changed files you can run git checkout -- * to get back the original file names locally.

3
Klas Mellbourn On

If you have done no other changes (that you want to keep) since the last commit, you can do

git reset --hard
0
zedd45 On

In my case, I moved an entire folder, then realized I should not have.

I really liked @Dave Konopka's answer, but I did not have much success with that approach (maybe my version of GIT (1.8.4)? My files still showed as deleted. I had other changes on the stack that I did not want to lose (unfortunately).

I did have success doing this:

git reset moved_folder
git checkout original_folder
2
zbig On
git reset HEAD file2

did the trick for me

0
Kamaraju Kusumanchi On
git reset HEAD file2
git checkout -- file1
rm file2

The first command unstages file2 but leaves a copy of it around. The second command restores the original file and the third deletes the new file.

0
sevencontinents On

The trick I used was to do a git stash to undo all my changes (which includes restoring the mv'd files) and then deleted the stash with git stash drop.

1
w0mbat On

Less scary is to go to top level of the repo and do:

git reset
git checkout .

0
Richard On

I liked @Kamaraju Kusumanchi's answer. However, I could not properly checkout file1 because it was staged for deletion at that point. So a better answer may be

git reset HEAD file2 file1
git checkout -- file1
rm file2

I actually did the reset in two steps since I was following Kamaraju's suggestion. So the reset might need to be done in two steps. Simply said, resetting just file2 leaves file1 staged for deletion. So both the rename and the deletion need to be unstaged before reverting file1 with a checkout.