Git: Add only modified / deleted files and ignore new files ( i.e. Untracked files ) using “git add -u”

How to add only modified / deleted files and ignore new files ( i.e. Untracked files ) using “git add -u”

In this article we will discuss about adding only modified / deleted files and ignore new files ( i.e. Untracked files ) using “git add -u”. So let’s go through the article to understand this.

Command to skip new files / folders while adding other files to git :

Sometimes we need to add only the old files that previously existed and not the newly created ones. This can be done by the following commands. Here git only adds the files whom Git previously knows.

$ git add -u <pathspec>

OR

$ git add --update <pathspec>

The <pathspec> is used to specify the path from which the files are to be added. It might be a particular file, a folder or all the files and folders under the project.

To add all the existing or deleted files and folders to the staging area, we can use

$ git add -u

Example :

We will first check the status of our git project in the master branch

$ git status

Output :
On branch master
Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified:   imp.md
modified:  notes.txt
deleted:    ignore.md
Untracked files:
(use "git add <file>..." to include in what will be committed)
build.xml
include/
src/
test/
no changes added to commit (use "git add" and/or "git commit -a")

We have following changes waiting to be added in staging area of git,

  1. Many untracked files i.e. new files, folders, sub folders and files under those folders.
  2. Two modified tracked files i.e README.md and notes.txt
  3. One tracked file is deleted i.e. ignore.md

Now we run the command

$ git add -u      

Output :
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified:   imp.md
modified:  notes.txt
deleted:    ignore.md
Untracked files:
(use "git add <file>..." to include in what will be committed)
build.xml
include/
src/
test/

Finally we commit

$ git commit -m "Adding only modified & deleted files."

We can check the status now, the untracked files will still be there.

$ git status
Output :
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
build.xml
include/
src/
test/
nothing added to commit but untracked files present (use "git add" to track)

So that’s how we can add only the tracked files and skip the new files.