x=$(find . -name \"*.txt\")
echo $x
if I run the above piece of code in Bash shell, what I get is a string containing several file names separated
What ever you do, don't use a for loop:
# Don't do this
for file in $(find . -name "*.txt")
do
…code using "$file"
done
Three reasons:
find must run to completion.for loop returns 40KB of text. That last 8KB will be dropped right off your for loop and you'll never know it.Always use a while read construct:
find . -name "*.txt" -print0 | while read -d $'\0' file
do
…code using "$file"
done
The loop will execute while the find command is executing. Plus, this command will work even if a file name is returned with whitespace in it. And, you won't overflow your command line buffer.
The -print0 will use the NULL as a file separator instead of a newline and the -d $'\0' will use NULL as the separator while reading.