Add All Files for Commit Except One File

This article illustrates how you can add all files for commit while excluding a file of your choosing. This comes in handy when you have many files you want to include in a commit and must leave out a single file.

πŸ”΄ Best Practice: Configure and O...
πŸ”΄ Best Practice: Configure and Optimize Setting.py File in Django 2020

Instead of adding a file at a time, you can follow these simple steps.

Add All Files for Commit Except One File

Take a look at the example below. Assuming we have over twenty modified files, how do we add all of them except one?

Let’s say we want to exclude a requirements.txt file from the index. How would we go about this?

We can employ several commands to exclude our requirements.txt file while staging. These are:

  1. Unstage with the git reset command.
  2. Use the Exclude Pathspec.
  3. Temporarily exclude the file from tracking.

Use the git reset Command

When using the git reset command, you must add all the files to the index and then unstage the file you want.

Syntax:

# Start by staging all files
$ git add .
# To exclude a file
$ git reset -- path/to/file
# To exclude a folder
$ git reset -- path/to/folder/*

In our case, we will add all the files and unstage the requirements.txt file, as illustrated below.

$ git add .

This will stage all the files. To unstage the requirements.txt file, we will run:

$ git reset -- path/to/requirements.txt

This command should unstage our requirements.txt file.

Use the Exclude Pathspec

Git version 1.9.0 and higher allows us to remove one or more paths while adding files for commit. This is possible with the :(exclude) pathspec, also written as :! or :^.

Here is an example.

$ git add --all -- ':!path/to/requirements.txt'

To exclude a folder:

$ git add --all -- ':!path/to/folder/*'

Temporarily Exclude File From Tracking

We can temporarily exclude our requirements.txt file from tracking, as illustrated below.

$ git update-index --assume-unchanged path/to/requirements.txt

Git will exclude our requirements.txt file every time we run the git add . command. To list all the files marked --assume-unchanged, we will run:

$ git ls-files -v | grep "^h"

To remove our file from the excluded list, we will run:

$ git update-index --no-assume-unchanged path/to/requirements.txt

In a nutshell, there are several ways of adding all files except one to the index. As we have discussed, temporarily excluding files from tracking is the cleanest and most efficient.

Related Article - Git Add

  • Undo the Git add Command
  • Add All Files in a Folder to Commit in Git
  • Staging Area in Git
  • Related Article - Git Commit

  • Undo the Git add Command
  • Add All Files in a Folder to Commit in Git
  • Staging Area in Git