Blogmark
Git Pathspecs and How to Use Them
via jbranchaud@gmail.com
Pathspecs are an integral part of many git commands, but their flexibility is not immediately accessible. By learning how to use wildcards and magic signatures you can multiply your command of the git command line.
I recently learned how to use a pathspec magic signature to exclude a directory from a git command.
$ git restore --patch -- . ':!spec/cassettes'
So, I was curious to learn more about this syntax, other magic signatures, and what all falls under the umbrella of a pathspec. I did some digging in the man pages and the main source of information I could find was a section on pathspec
in the man gitglossary
page. The descriptions here were fairly terse and didn't include examples.
Fortunately, Adam Giese wrote this excellent blog post on CSS Tricks covering the topic. It goes through everything from "what is a pathspec in its simplest form?" to "how to use the various magic signatures".
Here are two examples Adam gives of doing an exclude:
git grep 'foo' -- '*.js' ':(exclude)*.spec.js' # search .js files excluding .spec.js
git grep 'foo' -- '*.js' ':!*.spec.js' . # shorthand for the same
And here is an example of combining several magic signatures:
git ls-files -- ':(top,icase,glob,attr:!vendored)src/components/*/*.jsx'
Adam also pulled this amazing line from the man gitglossary
page:
Glob magic is incompatible with literal magic.