Git Tutorial - File Operation

Jinku Hu Feb 06, 2022 Jul 19, 2018
  1. Git Delete Files
  2. Git Rename Files
  3. Git Move Files
Git Tutorial - 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 file test2.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)


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

The drawback of such an 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.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.