Git File Operation

In this tutorial, You will learn the file operation in git, like delete, move and rename files.

Git delete files

The easiest way to delete files from the tracking and eventually from the repository is git rm

$ git rm tes2.txt
rm 'test2.txt'

After you run this command, the filetest2.txt is deleted from the working folder and this delete information has been added to the staging area.

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

	deleted:    test2.txt

Git rename files

If you rename the file in your working copy directly, git regards this operation as two operations, the first one is to delete the files with the old new, and the second one is to add the newly-named file to the working copy.

$ git status
On branch master
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:    test1.txt

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

	test1_rename.txt

no changes added to commit (use "git add" and/or "git commit -a")

The drawback of such operation is that it breaks the revision history of the file, and you could not get the revision history of this newly-named file earlier than this renaming moment. It is not desirable in the version control.

Git has a rename command to solve this broken linkage issue - mv

$ git mv test1.txt test1_rename.txt

mv means actually means move, but here, moving from test1.txt to test1_rename.txt also means renaming the file.

If you check the git status now, renamed appears,

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

	renamed:    test1.txt -> test1_rename.txt

Git move files

Similar to renaming files, moving files in the git also uses git mv command, but the file destination is not the same directory of the moved file.

$ git mv test1_rename.txt move/test1.txt

Here, move is the destination directory, and test1.txt is the new name of the moved file test1_rename.txt.

Let’s check the git status,

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

	renamed:    test1_rename.txt -> move/test1.txt

You could see, it is also a renamed operation, but with a different destination.