The problem
Sometimes you want to add all files to git except some files or folders.
The solution
You can use the :(exclude)
syntax to exclude files or folders from the git add
command. The :(exclude)
pathspec modifier is a special syntax that allows you to exclude files or folders. A pathspec is a way to specify files in Git. It is a string that describes a set of files. You can use wildcards to match multiple files. For example, *.html
matches all html files. **/*.html
matches all html files in all subfolders.
Instead of :(exclude)
you can use the shorthand :!
or :^
syntax. For example, :!*.html
or :^*.html
will exclude all html files.
Exclude a single file
For example, to add all files except the abc.txt
file, you can use the following command:
git add --all -- ':(exclude)file/path/for/abc.txt'
# or using the shorthand syntax:
git add --all -- ':!file/path/for/abc.txt'
Note: Don’t forget to add a space between the
--
and the:(exclude)
syntax.
Note: The
--all
flag is used to add all files. If you don’t use the--all
flag, then you can use the.
to add all files in the current directory.
Exclude multiple files
For example, to add all files except the abc.txt
and xyz.txt
files, you can use the following command:
git add --all -- ':(exclude)file/path/for/abc.txt' ':(exclude)file/path/for/xyz.txt'
# or using the shorthand syntax
git add --all -- ':!file/path/for/abc.txt' ':!file/path/for/xyz.txt'
Exclude files of a certain type
For example, to add all files except the html files (in the current directory), you can use the following command:
git add --all -- ':(exclude)*.html'
# or using the shorthand syntax
git add --all -- ':!*.html'
Exclude a folder
git add --all -- ':(exclude)path/to/exclude'
git add --all -- ':(exclude)path/to/exclude1' ':(exclude)path/to/exclude2'
git add --all -- ':(exclude)path/to/exclude1' ':(exclude)path/to/exclude2' ':(exclude)path/to/exclude3'
Exclude files of a certain type in a folder
For example, to add all files except the html files in the static
folder, you can use the following command:
git add --all -- ':(exclude)static/*.html'
Exclude files of a certain type in a folder and its subfolders
For example, to add all files except the html files in the static
folder and its subfolders, you can use the following command:
git add --all -- ':(exclude)static/**/*.html'