How to loop through file names returned by find?

前端 未结 13 1342
野性不改
野性不改 2020-11-22 04:20
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

13条回答
  •  执念已碎
    2020-11-22 04:35

    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:

    • For the for loop to even start, the find must run to completion.
    • If a file name has any whitespace (including space, tab or newline) in it, it will be treated as two separate names.
    • Although now unlikely, you can overrun your command line buffer. Imagine if your command line buffer holds 32KB, and your 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.

提交回复
热议问题