How to Add All Files to a Git Commit Except Some?

Using the Exclude Pathspec

Available since git v1.9.0, the :(exclude) pathspec (shorthand :! or :^) can be used to remove one (or more) paths from the included paths. For example, to add all paths except one/some, we could do either of the following:

git add --all -- ':!path/to/file1.txt' ':!path/to/file2.txt' ':!path/to/folder1/*'

# or:
git add -- . -- ':!path/to/file1.txt' ':!path/to/file2.txt' ':!path/to/folder1/*'

You can also use this syntax to specify wildcard patterns for matching files/folders. For example, the following includes all .js files but excludes all .spec.js files:

git add -- '*.js' -- ':(exclude)*.spec.js'

# or, shorthand:
git add -- '*.js' -- ':!*.spec.js'

Up until git v2.12, when using an exclude pathspec, you must specify at least one pathspec that adds path(s).

Using git reset

You can use any command to add all files you wish to stage (like git add . for example), followed by git reset to unstage the ones you want to exclude:

git add .

# excluding file:
git reset -- path/to/file.txt

# excluding folder:
git reset -- path/to/folder/*

Temporarily Excluding File From Tracking

It can quickly become tedious and cumbersome to exclude file(s) each time you do git add, etc. Luckily, we can temporarily exclude a file from being tracked altogether using the following command:

git update-index --assume-unchanged path/to/file.txt

This would ensure that the specified file does not get added to the staging area when you execute something (like git add .) to add/stage all files.

This works with files only, and won't work with directories. There are some workarounds for that, but it is beyond the scope of this article so we won't get into those.

You can get a list of files marked --assume-unchanged by using the following command:

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

When/if you wish to allow the excluded file to be staged again, you could use the following command:

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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.