762

I've moved a file manually and then I've modified it. According to Git, it is a new file and a removed file. Is there any way to force Git into treating it as a file move?

7

15 Answers 15

608

Git will automatically detect the move/rename if your modification is not too severe. Just git add the new file, and git rm the old file. git status will then show whether it has detected the rename.

additionally, for moves around directories, you may need to:

  1. cd to the top of that directory structure.
  2. Run git add -A .
  3. Run git status to verify that the "new file" is now a "renamed" file

If git status still shows "new file" and not "renamed" you need to follow Hank Gay’s advice and do the move and modify in two separate commits.

14
  • 133
    Clarification: 'not too severe' means that the new file and old file are >50% 'similar' based on some similarity indexes that git uses.
    – pjz
    Oct 19, 2010 at 20:10
  • 244
    Something that hung me up for a few minutes: if the renamed files and deleted files are not staged for committing then they will show up as a delete and a new file. Once you add them to the staging index it will recognize it as a rename.
    – marczych
    Mar 14, 2012 at 1:41
  • 31
    It is worth mentioning that when speaking of "Git will automatically detect the move/rename". It does so at the time you use git status, git log or git diff, not at the time you do git add, git mv or git rm. Further speaking of detecting rename, that only makes sense for staged files. So a git mv followed by a change in the file may look in git status as if it considers it as a rename, but when you use git stage (same as git add) on the file, it becomes clear that the change is too large to be detected as a rename.
    – Jarl
    Sep 4, 2012 at 8:14
  • 18
    This isn't infallible though, especially if the file changed and is small. Is there a method to specifically tell git about the move?
    – Rebs
    Jun 8, 2016 at 0:56
  • 19
    @YarekT Its not purely a cosmetic feature, because if git on commit has detected a rename, then viewing history on that file will give history back across the old filename. Which to me is the point of a rename vs delete+add. (Tested on git 2.20)
    – arberg
    Jul 6, 2019 at 9:17
189

Do the move and the modify in separate commits.

18
  • 21
    I understand that Git is can handle moves and modifications at the same time. When programming in Java and using an IDE, renaming a class is both a modification and a move. I understand that Git even should be able to automatically figure it out when there's a move (out of a remove and a creation). Jan 11, 2009 at 16:19
  • 11
    @jrockway, I had. Happens easily with small files, I guess they "become 'too different' to mean a move".
    – ANeves
    Dec 15, 2010 at 16:24
  • 12
    One thing to note is that if git diff doesn't recognize the rename across one commit, it won't recognize it across two commits. You would need use -M aka --find-renames to do that. So if the motivation that led you to this question is to see the rename in a pull request (speaking from experience), splitting it into two commits will not further you towards that goal.
    – mattliu
    Mar 2, 2017 at 6:21
  • 5
    This seems like a low knowledge answer. An advanced version control system such as GIT should have a method of setting an added file as a renamed of a deleted one inside one commit.
    – cdalxndr
    Apr 8, 2020 at 20:54
  • 7
    @cdalxndr The fact that Git doesn't have a method to mark a rename has nothing to do with the quality of this answer.
    – KenIchi
    Jul 14, 2020 at 11:32
55

git diff -M or git log -M should automatically detect such changes as a rename with minor changes as long as they indeed are. If your minor changes are not minor, you can reduce the similarity threashold, e.g.

$ git log -M20 -p --stat

to reduce it from the default 50% to 20%.

2
  • 21
    Is it possible to define threshold in the config? Feb 12, 2016 at 11:56
  • 1
    It is the same "interactive window" that git log by itself provides, which allows in-terminal scrolling and exit with q. don't worry, it would be difficult to screw something up in a git log view by itself. May 28, 2021 at 15:55
46

It's all a perceptual thing. Git is generally rather good at recognising moves, because GIT is a content tracker

All that really depends is how your "stat" displays it. The only difference here is the -M flag.

git log --stat -M

commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date:   Fri Jan 9 22:13:51 2009 +1300


        Category Restructure

     lib/Gentoo/Repository.pm                |   10 +++++-----
     lib/Gentoo/{ => Repository}/Base.pm     |    2 +-
     lib/Gentoo/{ => Repository}/Category.pm |   12 ++++++------
     lib/Gentoo/{ => Repository}/Package.pm  |   10 +++++-----
     lib/Gentoo/{ => Repository}/Types.pm    |   10 +++++-----
     5 files changed, 22 insertions(+), 22 deletions(-)

git log --stat

commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date:   Fri Jan 9 22:13:51 2009 +1300

    Category Restructure

 lib/Gentoo/Base.pm                |   36 ------------------------
 lib/Gentoo/Category.pm            |   51 ----------------------------------
 lib/Gentoo/Package.pm             |   41 ---------------------------
 lib/Gentoo/Repository.pm          |   10 +++---
 lib/Gentoo/Repository/Base.pm     |   36 ++++++++++++++++++++++++
 lib/Gentoo/Repository/Category.pm |   51 ++++++++++++++++++++++++++++++++++
 lib/Gentoo/Repository/Package.pm  |   41 +++++++++++++++++++++++++++
 lib/Gentoo/Repository/Types.pm    |   55 +++++++++++++++++++++++++++++++++++++
 lib/Gentoo/Types.pm               |   55 -------------------------------------
 9 files changed, 188 insertions(+), 188 deletions(-)

git help log

   -M
       Detect renames.

   -C
       Detect copies as well as renames. See also --find-copies-harder.
12
  • 108
    Sorry if this seems a bit pedantic, but "Git is generally rather good at recognising moves, because GIT is a content tracker" seems like a non-sequitur to me. It's a content tracker, yes, and perhaps it happens to be good at detecting moves, but the one statement doesn't really follow from the other. Just because it's a content tracker the move detection isn't necessarily good. In fact, a content tracker could have no move detection at all. Sep 10, 2010 at 23:48
  • 1
    @WarrenSeine when you rename a directory, the SHA1's of the files in that directory do not change. All you have is a new TREE object with the same SHA1s. There's no reason a directory rename would cause significant data changes. Feb 27, 2014 at 21:53
  • 1
    @KentFredric You showed that using -M with "git log" we can check whether file is renamed or not and i tried it and its working fine, but when i post my code for review and see that file in gerrit (gerritcodereview.com) there it shows the file is newly added and previous was deleted. So is there an option in "git commit" using which i do commit and gerrit shows it properly.
    – Patrick
    May 7, 2016 at 11:57
  • 2
    No. I didn't show that at all. I showed Git is capable of pretending an add + delete is a rename due to the content being the same. There's no way for it to know which happened, and it doesn't care. All git remembers is "added" and "deleted". "Renamed" is never recorded. May 7, 2016 at 13:05
  • 1
    For example, I did a lot of "Copy + Edit" on a repo lately. Most ways of viewing it only see "new file", but if you pass git log -M1 -C1 -B1 -D --find-copies-harder, git can "discover" that the new file might have been copied first. Sometimes it does this right, other times, it finds entirely unrelated files that happened to have identical content. May 7, 2016 at 13:07
46

Here's a quick and dirty solution for one, or a few, renamed and modified files that are uncommitted.

Let's say the file was named foo and now it's named bar:

  1. Rename bar to a temp name:

    mv bar side
    
  2. Checkout foo:

    git checkout HEAD foo
    
  3. Rename foo to bar with Git:

    git mv foo bar
    
  4. Now rename your temporary file back to bar.

    mv side bar
    

This last step is what gets your changed content back into the file.

While this can work, if the moved file is too different in content from the original git will consider it more efficient to decide this is a new object. Let me demonstrate:

$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ git add README.md work.js # why are the changes unstaged, let's add them.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ git stash # what? let's go back a bit
Saved working directory and index state WIP on dir: f7a8685 update
HEAD is now at f7a8685 update
$ git status
On branch workit
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .idea/

nothing added to commit but untracked files present (use "git add" to track)
$ git stash pop
Removing README
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README
    modified:   work.js

Dropped refs/stash@{0} (1ebca3b02e454a400b9fb834ed473c912a00cd2f)
$ git add work.js
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README

$ git add README # hang on, I want it removed
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ mv README.md Rmd # Still? Try the answer I found.
$ git checkout README
error: pathspec 'README' did not match any file(s) known to git.
$ git checkout HEAD README # Ok the answer needed fixing.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README.md
    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ git mv README README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ mv Rmd README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ # actually that's half of what I wanted; \
  # and the js being modified twice? Git prefers it in this case.
8
  • 36
    This process serves no purpose. git doesn't add any metadata for renames, git mv is simply a convenience for a git rm/git add pair. If you've already done 'mv bar foo', then all you have to do is make sure that you've git add foo and git rm bar before making the commit. This could be as done as a single git add -A command, or possibly a git add foo; git commit -a sequence.
    – CB Bailey
    Oct 9, 2009 at 6:48
  • 23
    All I know is that before I did it, Git didn't recognize it as a move. After I did this, Git recognized it as a move.
    – user186821
    Oct 15, 2009 at 0:35
  • 10
    It recognizes it as a move. But it also has the change as an unstaged change now. Once you add the file again, git breaks the move/modify into a deleted/added again. Feb 22, 2012 at 8:30
  • 6
    This process would work if you git commit after step 3, otherwise it is incorrect. Also, @CharlesBailey is correct, you could as easily do a normal mv blah foo at step 3 followed by a commit and get the same results.
    – DaFlame
    Feb 7, 2014 at 15:36
  • 6
    "This process serves no purpose." - It serves a purpose when git has gotten confused and thinks a file has been deleted, and another file has been added. This clears up Git's confusion and marks the file as moved explicitly without having to do intermediate commits.
    – Danack
    Jun 6, 2015 at 14:50
37

You could try Amber's answer to another question! To quote it again:

First, cancel your staged add for the manually moved file:

$ git reset path/to/newfile
$ mv path/to/newfile path/to/oldfile

Then, use Git to move the file:

$ git mv path/to/oldfile path/to/newfile

Of course, if you already committed the manual move, you may want to reset to the revision before the move instead, and then simply git mv from there.

3
  • 10
    Note that this does not work if you also have substantial changes, which happens usually on small files. It gets committed as 'delete' and 'create'. In such case I guess the only option is to "Do the move and the modify in separate commits" as suggested on another answer. Nov 12, 2020 at 13:44
  • @AlbertVilaCalvo Are you sure? You have to do this last, right before committing (that is, you can't run git mv, edit more, and then have this work), but I just edited > 50% of a file and renamed/moved it in one commit. In other words, you have to edit before performing git mv afaict.
    – ruffin
    Sep 15 at 20:13
  • @ruffin at first git mv oldfile newfile the git status registers the change as modified: newfile, but after git add newfile the status changes to deleted: oldfile and new file: newfile anyway
    – Efigie
    Oct 29 at 22:41
24

If you're talking about git status not showing the renames, try git commit --dry-run -a instead

0
11

If you're using TortoiseGit it's important to note that Git's automatic rename detection happens during commit but the fact that this is going to happen isn't always displayed by the software beforehand. I had moved two files to a different directory and performed some slight edits. I use TortoiseGit as my commit tool and the Changes made list showed the files being deleted and added, not moved. Running git status from the command line showed a similar situation. However after committing the files, they showed up as being renamed in the log. So the answer to your question is, as long as you haven't done anything too drastic, Git should pick up the rename automatically.

Edit: Apparently if you add the new files and then do a git status from the command line, the rename should show up before committing.

Edit 2: In addition, in TortoiseGit, add the new files in the commit dialog but don't commit them. Then if you go into the Show Log command and look at the working directory, you'll see if Git has detected the rename before committing.

The same question was raised here: https://tortoisegit.org/issue/1389 and has been logged as a bug to fix here: https://tortoisegit.org/issue/1440 It turns out it's a display issue with TortoiseGit's commit dialog and also kind of exists in git status if you haven't added the new files.

2
  • 2
    You are right, even if TortoiseGit shows delete + add, even if git status shows delete + add even if git commit --dry-run shows delete + add, after git commit I see rename and not delete + add. May 9, 2014 at 11:40
  • 1
    I'm pretty sure the automatic rename detection happens during history retrieval; in the commit it is always add+delete. That also explains the schizophrenic behavior you describe. Hence the options here: stackoverflow.com/a/434078/155892
    – Mark Sowul
    Mar 24, 2016 at 18:59
11

The other answers already cover that you can simply git add NEW && git rm OLD in order to make git recognize the move.

However, if you have already modified the file in the working directory, the add+rm approach will add the modifications to the index, which may be undesired in some cases (e.g. in case of substantial modifications, Git might not recognize anymore that it is a file rename).

Let's assume you want to add the rename to the index, but not any modifications. The obvious way to achieve this, is to do a back and forth rename mv NEW OLD && git mv OLD NEW.

But there is also a (slightly more complicated) way to do this directly in the index without renaming the file in the working tree:

info=$(git ls-files -s -- "OLD" | cut -d' ' -f-2 | tr ' ' ,)
git update-index --add --cacheinfo "$info,NEW" &&
  git rm --cached "$old"

This can also be put as an alias in your ~/.gitconfig:

[alias]
    mv-index = "!f() { \
      old=\"$1\"; \
      new=\"$2\"; \
      info=$(git ls-files -s -- \"$old\" | cut -d' ' -f-2 | tr ' ' ,); \
      git update-index --add --cacheinfo \"$info,$new\" && \
      git rm --cached \"$old\"; \
    }; f"
2
  • +1, sadly there is no way to do that directly with git mv, like ex with --cached in git rm. In my case I moved an entire directory, so I use a slightly different way: git ls-files -s -- OLD |sed 's#\tOLD/#\tNEW/#' followed with git rm -r --cached OLD. NB: the \t and trailing / in sed match the Tab char preceding the path and the directory separator, use the full path from the root of your repo (this ensures you match only that dir and not any similarly named file/directory). May 30, 2022 at 4:20
  • For the sake of completeness, you should show how to use the mv-index.
    – Bolpat
    Oct 19 at 11:59
8

Use git mv command to move the files, instead of the OS move commands: https://git-scm.com/docs/git-mv

Please note that git mv command only exists in Git versions 1.8.5 and up. So you may have to update your Git to use this command.

0
4

I had this problem recently, when moving (but not modifying) some files.

The problem is that Git changed some line endings when I moved the files, and then wasn't able to tell that the files were the same.

Using git mv sorted out the problem, but it only works on single files / directories, and I had a lot of files in the root of the repository to do.

One way of fixing this would be with some bash / batch magic.

Another way is the following

  • Move the files and git commit. This updates the line endings.
  • Move the files back to their original location, now that they have the new line endings, and git commit --amend
  • Move the files again and git commit --amend. There is no change to the line endings this time so Git is happy
0

For me it worked to stash save all the changes before the commit and pop them out again. This made git re-analyze the added / deleted files and it correctly marked them as moved.

0
0

The way I understand this question is "How to make git recognize a deletion of an old file and creation of a new file as a file move".

Yes in the working directory once you delete an old file and inserted an old file, git status will say "deleted: old_file" and "Untracked files: ... new_file"

But in the staging index/level once you add and remove file using git it will be recognized as a file move. To do so, assuming you have done the deletion and creation using your Operation System, give the following commands:

git add new_file
git rm old_file

If the contents of the file are 50% or more similar, running git status command should give you:

renamed: old_file -> new_file
1
-1

There is a probably a better “command line” way to do this, and I know this is a hack, but I’ve never been able to find a good solution.

Using TortoiseGIT: If you have a GIT commit where some file move operations are showing up as load of adds/deletes rather than renames, even though the files only have small changes, then do this:

  1. Check in what you have done locally
  2. Check in a mini one-line change in a 2nd commit
  3. Go to GIT log in tortoise git
  4. Select the two commits, right click, and select “merge into one commit”

The new commit will now properly show the file renames… which will help maintain proper file history.

1
  • The result of doing this is the same as moving and modifying the file in the same commit . It simply does not work.
    – Jolta
    Jun 28 at 11:19
-3

When I edit, rename, and move a file at the same time, none of these solutions work. The solution is to do it in two commits (edit and rename/move seperate) and then fixup the second commit via git rebase -i to have it in one commit.

1
  • 1
    -1: The result of doing this is the same as moving and modifying the file in the same commit -- just with extra steps. It doesn't work. Dec 17, 2020 at 12:07

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.