Using git mv

Suppose you need to move or rename a file. You may use a combination of git rm on the old file and git add on the new file, or you may use git mv directly. Given a repository with a file named stuff that you want to rename newstuff, the following sequences of commands are equivalent Git operations:

$ mv stuff newstuff
$ git rm stuff
$ git add newstuff

and

$ git mv stuff newstuff

In both cases, Git removes the pathname stuff from the index, adds the new pathname newstuff, keeps the original content for stuff in the object store, and reassociates that content with the pathname newstuff.

With data back in the example repository, let’s rename it and commit the change:

$ git mv data mydata

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       renamed:    data -> mydata
#

$ git commit -m"Moved data to mydata"
Created commit ec7d888: Moved data to mydata
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename data => mydata (100%)

If you happen to check the history of the file, you may be a bit disturbed to see that Git has apparently lost the history of the original data file and remembers only that it renamed data to the current name:

$ git log mydata
commit ec7d888b6492370a8ef43f56162a2a4686aea3b4
Author: Jon Loeliger <jdl@example.com>
Date:   Sun Nov 2 19:01:20 2008 -0600

    Moved data to mydata

Git does still remember the whole history, but the display is limited to the particular filename you specified in the command. The --follow ...

Get Version Control with Git now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.