21

I try to search for files that may contain white spaces I try to use -print0 and set IFS here is my script

IFS=$'\0';find people -name '*.svg' -print0 | while read file; do
    grep '<image' $file > /dev/null && echo $file | tee -a embeded_images.txt;
done

I try to fine all svg file containing embeded images, it work without -print0 but fail one one file so I stop the script. Here is simpler example that don't work too

IFS=$'\0';find . -print0 | while read file; do echo $file; done

it don't display anything.

2 Answers 2

29

Though Dennis Williamson's answer is absolutely correct, it creates a subshell, which will prevent you from setting any variables inside the loop. You may consider using process substitution, as so:

while IFS= read -d '' -r file; do
    grep '<image' "$file" > /dev/null && echo "$file" | tee -a embeded_images.txt
done < <(find people -name '*.svg' -print0)

The first < indicates that you're reading from a file, and the <(find...) is replaced by a filename (usually a handle to a pipe) that returns the output from find directly. Because while reads from a file instead of a pipe, your loop can set variables that are accessible from outside the scope.

Sign up to request clarification or add additional context in comments.

Comments

27

Use read -d '' -r file and set IFS only for the context of read:

find people -name '*.svg' -print0 | while IFS= read -d '' -r file; do
    grep '<image' "$file" > /dev/null && echo "$file" | tee -a embeded_images.txt;
done

And quote your variables.

3 Comments

The @IFS= read@ approach succeeds on files ending with spaces
Strange read -d'' -r file; do don't work but with space -d '' does.
@jcubic: The content of the single quotes is null. Bash sees -d'' as one argument. When it does quote removal there's nothing left but -d. It sees -d '' as two arguments, one of which is null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.