#9 Git: Renaming and moving files in git

In this post, we will take a look at the commands to rename and remove the files in the git repository. We will see what happens if we try to remove or rename the files using windows options(without git commands).

Now here I am renaming sample.txt to first.txt.

After renaming sample.txt to first.txt I’ll run git status command, it gives me following result:

Above it is saying that sample.txt is deleted and first.txt is a newly created file which is untracked. But when I add it in the staging area and again check the status it shows me the following result:

When we added the changes to the staging area git recognized that we have renamed our sample.txt to first.txt. So this is what happens when we try to rename the file with windows options we have to explicitly add it in the staging area.

Renaming files with the git command

We will try to rename second.txt to renamed_second.txt using following git command:

git mv original_filename.extension renamed_filename.extension

As we can see second.txt is now renamed as renamed_second.txt and git also recognized the change without adding the changes into staging area.

Deleting files in git

The same thing happens when we delete a file, git will not stage the changes automatically if we are deleting it by windows delete options. But git stages the changes automatically when we try to delete it with git command so the command is as follows:

git rm file_name.extension

So as you can see above command deleted the first.txt file and also staged the changes.

Now there is another use of the rm command i.e. when we have to remove any file from the tracking stage we use it with different options like here I am already tracking the example.txt file so whenever I make the change to it, it shows the effect on the git repository.

As I make changes in the example.txt and run git status it shows me modified because git is tracking that file, to untrack that file we will use the following command:

git rm --cached file_name.extension

Now as you can see example.txt is showing as an untracked file and also it is showing deleted but actually, it is not deleted, it is present in the folder but git is not tracking it means any changes made into it will not be committed.

Leave a Comment

Your email address will not be published. Required fields are marked *