0

I'm trying to run the script below and I'm struggling with pathspec error when the filename has whitespaces.

I have already read some other posts around here, but since I am not an expert I was not able to convert the ideas in a solution to this piece of code.

#!/bin/sh
#
for file in $(git grep -l -i '#private') ; do
    git rm "$file"
    echo "$file is private."
done

Does anyone have an idea?

Thanks in advance.

1 Answer 1

2

Short answer: see BashFAQ #20: "How can I find and safely handle file names containing newlines, spaces or both?". Also, you should almost never use for var in $(something) -- it treats all whitespace as delimiters, tries to expand anything that looks like a wildcard, and generally does things you don't want it to do.

Solution: Use git grep --null to get null-delimited output, and use a while IFS= read -r -d '' loop to read filenames from that:

#!/bin/bash
#
while IFS= read -r -d '' file; do
    git rm "$file"
    echo "$file is private."
done < <(git grep -l --null -i '#private')

Note that this uses several bash features that other shells may not support, so it's important that it be run with bash, not just plain sh.

You must log in to answer this question.

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