How do I exclude files from git ls-files?

You do not need to use the --exclude parameter because this key is only used for skipping untracked files:

$ man git-ls-files

-x <pattern>, --exclude=<pattern>
       Skip untracked files matching pattern. Note that pattern is a shell wildcard pattern. See EXCLUDE PATTERNS below for more information.

You should just use a mask for required files

In your case (excluding *.md files):

$ git ls-files
example1.txt
example2.pdf
readme.md

$ git ls-files *[^.md]
example1.txt
example2.pdf

Git has its own way to extend glob patterns, and that includes a way to exclude files that match one pattern but not another. For example, the following will list all paths not ending in .md:

git ls-files -- . ':!:*.md'

It's important to quote the pattern, because you want git to parse it, not the shell.

And to match all files ending with .js, except the ones ending with .min.js:

git ls-files -- '*.js' ':!:*.min.js'

You can also use this with other commands, such as git grep:

git grep -w funcname -- '*.js' ':!:*.min.js'

This syntax is explained under pathspec in gitglossary (or git help glossary or man gitglossary)


How about using a grep reverse match -v?

git ls-files | grep -v -E "\.md$"

That was already discussed in 2010:

There is no indication in the man page that -x doesn't apply to -c.

Hence the addition:

Since b5227d8, -x/--exclude does not apply to cached files.
This is easy to miss unless you read the discussion in the EXCLUDE PATTERNS section. Clarify that the option applies to untracked files and direct the reader to EXCLUDE PATTERNS.

The git ls-files man page does mentions:

-x <pattern>
--exclude=<pattern>

Skip untracked files matching pattern

If your Readme.md is tracked, the exclude pattern won't apply.

Tags:

Git

Bash