Search code examples
bashgitgrepdiff

Return list using git diff and grep


I'm using git diff to return the file names of files recently changed and l’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 -e "- name:"))

Any help would appreciated!

EDIT: Solved! By removing the recursion and setting the git diff to a different variable, the correct list was returned.

git_diff_files=($(git -C ${prov_dir} diff --name-only HEAD^ HEAD))

changed_files_full=($(printf "${dir}/%s " "${git_diff_files[@]}" ))
changed_files_ansible=($(find "${changed_files_full[@]}" -type f -print0 | xargs -0 grep -lw --include="*.yml" --exclude-dir="$excluded" -e "- name:"))

Solution

  • Use this, using the best practices to feed an array, and avoid the form:

    arr=( $(cmd) )
    

    instead, use:

    read -ra files < <(
        git -z -C "$dir" diff --name-only HEAD^ HEAD | grep -z '\.yml$'
    )
    printf '%s\n' "${files[@]}"
    

    The -z from git & grep are meant to parse even files with newlines or special characters.