Excluding Files in 'git add' Using Pathspec
31 May 2020When I use git to do version control in my projects, my typical flow would be the following:
- Initialize git repository (git init).
- Make changes to the code.
- Add the changes to the staging area (git add).
- Commit the changes to the local repository (git commit).
- Push changes to the remote repository (git push).
I made changes to my project and so had to commit them. Typically, I would stage these changes with git add -A
which adds all new and modified files to the staging area. There are some cases though that I wanted to exclude some files from being added to the staging area. One particular case is when I tested some modifications to a gem I am using. In my Gemfile, instead of using the default gem’s repository, I pointed the said gem to my local copy which I modified:
Running bundle install
would also modify Gemfile.lock
, so git would know that both the Gemfile and Gemfile.lock have been modified. But I didn’t want to add and commit these changes yet until I’m satisfied with my modifications.
I could manually add each of the files I wanted to add. Say if I have ten files I wanted to add, I could manually enter git add file1 file2 fileN
. This can get inefficient though, especially when you have a lot of files you wanted to add and perhaps just one file to exclude. So I searched online for an efficient way to get this done and came across this answer that worked for me.
Applying the answer in my context, I added my files and excluded Gemfile and Gemfile.lock with the following:
I looked at git add’s documentation to see what those additional options for git add
meant. The --
option separates command-line options from the list of files. In the case above, it separates the --all
option from the list of specified files. The ':!Gemfile*'
from the command above is an example of specifying a pathspec. A pathspec, based on the online documentation, is a pattern used to limit paths in Git commands. A pathspec with a colon (:), in a nutshell, lets you exclude certain paths and files. When using git add
to exclude files or directories using pathspec magic, you may use its long form:
or its short form:
It can be used with other git commands aside from git add
. But knowing I can easily exclude files and directories when adding/staging changes is enough for me now.