I'm using git diff to return the file names of files recently changed and i'm trying to pipe the returned file names into a grep expression that searches each file and returns the files that have "*.yml" in the file name and "- name:" in the actual file. However it seems like my code only returns all the files in the directory that match the conditions, basically ignoring the git diff.

files=($(git -C ${dir} diff --name-only HEAD^ HEAD | grep -rlw --include="*.yml" --exclude-dir=$excluded_paths-e "- name:"))

Any help would appreciated!

  • Please edit your question and copy&paste the output of git -C ${dir} diff --name-only HEAD^ HEAD, the output of the complete pipe git -C ${dir} diff --name-only HEAD^ HEAD | grep -rlw --include="*.yml" --exclude-dir=$excluded_paths-e "- name:" and add the expected result. Make sure to copy&paste exactly the command you run on your system. Variable expansions should be quoted --exclude-dir="$excluded_paths" and there must be a space between this and -e.
    – Bodo
    May 11 at 14:32

1 Answer 1


git diff --name-only produces a list of files; you need to give that list to grep in a form it will understand, i.e. as command-line arguments. One way to do this is

git -C "${dir}" diff -z --name-only HEAD^ HEAD | xargs -0 grep -lw --include="*.yml" --exclude-dir="$excluded_paths" -e "- name:"

I added -z so that the file names are separated by null bytes; the -0 xargs option specifies the same delimiter for use in xargs’ input. I removed the -r option from grep — that is used for recursive searches, which is counter-productive here since the exact list of files to check is given.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .