Bash filter out files with a given extension

I've added a pre-commit hook to run Rubocop against any files that are being staged for commit. However, Rubocop errors out when you give it a .png or .svg file. I've added those file extensions to the exclude block in .rubocop.yml but because I'm actually explicitly supplying files by name that doesn't seem to do the trick.

Here's my pre-commit script:

#!/usr/bin/env bash

set -e

git diff --staged --diff-filter=d --name-only | xargs bundle exec rubocop

I think the approach is grabbing the list of files from that git command and looping through them, filtering out any that are .png or .svg, but honestly I don't know how to do that. Any suggestions on filtering the files by extension?

3 answers

  • answered 2021-10-12 16:46 jonS90

    One idea might be to filter out those extensions using grep.

    git diff --staged --diff-filter=d --name-only \
      | grep --invert-match '\.\(png\|svg\)$' \
      | xargs bundle exec rubocop
    

  • answered 2021-10-12 22:03 Andy Waite

    There is a flag --only-recognized-file-types which I think will do what you need.

  • answered 2021-10-12 22:42 jthill

    git diff  --staged --diff-filter=d --name-only -- ':!*.png' ':!*.svg'
    

    or for easier control you could check attributes and set up the matching just in .gitattributes.

    Say git help glossary and hunt up pathspec, there's probably a quicker route to find the docs for it but that's the one I know.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum