3

I have the following code to run pylint on all files in a Git repository with file extension .py, fed by command substitution.

pylint $(git ls-files '*.py')

The script runs just fine except when there are no files matching the pattern. However, the pylint utility gives a verbose help message when it is called with no files, which is not what I want - I don't want to call pylint at all.

So, could I ask for some help on how best to test if any files match the filename pattern before calling pylint?

I'm a pylint and bash newbie.

1 Answer 1

3

Don't use a command substitution at all. Instead, pass the data from git ls-files to xargs using a pipe and let xargs run pylint on the generated list of files:

git ls-files -z '*.py' | xargs -0 -r pylint

This passes the list of files from the git command to xargs as a \0-delimited list. The xargs utility would run pylint with names read from git, but with -r, it would not run the utility if the list was empty.

This solves three issues:

  1. By passing the pathnames as a \0-delimited list, it supports files with names containing newlines and other whitespaces.
  2. By reading from the pipe and running pylint on as large batches of files as possible, we are able to handle the case when git ls-files produces so much data that using the command substitution would fail with "argument list too long".
  3. It does not run pylint if the list is empty.

This answer assumes using an xargs implementation that has the non-standard (but common) options -0 and -r.

2
  • i was thinking to something similar, like : xargs -a <(git ls-files -z '*.p') -ri -- pylint {} . But your is better. +1 Commented Apr 14, 2022 at 19:18
  • 1
    Awesome thanks for the response - a lot of learning points for me Commented Apr 14, 2022 at 19:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.