Only Commit Changes to Tracked Files in Git

I recently started using the command git add -u when preparing my code for commit via the command line. This helps me to only commit changes to tracked files. Not long ago I would occasionally make accidental commits of untracked file changes when using the command git add .

If you’re new to git, the git add command adds content from your working directory into the staging area, preparing it for inclusion in your next commit. In git add -u example above, the -u flag is a short form of --update , which says “only add the changes for files that are already tracked”. Compare this with the commonly used git add . or the similar git add -A, and git will add all changes to both tracked and untracked files to the staging area.

*Note: git add . adds all files in the current directory, while git add -A adds all files in the entire repository.

Git Add Examples

Let’s look at an example, using a file App.js, which has been modified, along with test-file.json, which is a new file that is currently untracked.

Using git add .

Here we see both files have been staged for commit. If we intend to add the new test-file.json to our git repo, this can be the right command to use.

Using git add -u

In this case only the tracked file is staged for commit. If there are changed files in your working directory that you don’t wish to commit, git add -u is a good command to prevent this from happening accidentally.

Use a .gitignore file

If you consistently have untracked file changes in your working directory, consider setting a .gitignore file in the root of the directory. This file tells git which directories or filename paths to ignore when watching for file changes. For example, when working with node modules it is usually a good idea to ignore the entire node_modules folder, especially if your code will be subject to a build process on deployment to production. Depending on your specific setup, you may be able to ignore files like package-lock.json. Here’s an example of a .gitignore file in one of my repos:

In this example git will ignore the files config.env and .DS_Store, along with the entire contents of the node_modules folder.

Some tips in this article were shared with me by my colleague Sal Ferrarello. If you’re a web developer and you don’t already follow Sal’s blog, you should check it out here.

the author profile picture

Ryan Neilson is a software developer from Nova Scotia, Canada, where he lives with his wife and their menagerie of pets. He has worked extensively with PHP, WordPress, JavaScript, React, SCSS and CSS. Ryan can be found professionally at News Corp, where he works as a lead software engineer.