有几种可行的方法来实现这一点。
如果您想紧贴原来的版本,可以这样做:
getlist() {
IFS=$'\n'
for file in $(find . -iname 'foo*') ; do
printf 'File found: %s\n' "$file"
done
}
如果文件名中有文字换行符,这仍然会失败,但空格不会破坏它。
但是,没有必要搞乱 IFS。这是我的首选方式:
getlist() {
while IFS= read -d $'\0' -r file ; do
printf 'File found: %s\n' "$file"
done < <(find . -iname 'foo*' -print0)
}
如果您对< <(command) 语法不熟悉,您应该阅读process substitution。与for file in $(find ...) 相比,它的优势在于可以正确处理带有空格、换行符和其他字符的文件。这是因为find 和-print0 将使用null(又名\0)作为每个文件名的终止符,并且与换行符不同,null 不是文件名中的合法字符。
与几乎同等版本相比的优势
getlist() {
find . -iname 'foo*' -print0 | while read -d $'\0' -r file ; do
printf 'File found: %s\n' "$file"
done
}
是否保留了 while 循环主体中的任何变量赋值。也就是说,如果你像上面那样通过管道传递给while,那么while 的主体就在一个子shell 中,这可能不是你想要的。
与find ... -print0 | xargs -0 相比,进程替换版本的优势很小:如果您只需要打印一行或对文件执行单个操作,但如果您需要执行多个步骤,则xargs 版本很好循环版本更容易。
编辑:这是一个很好的测试脚本,因此您可以了解解决此问题的不同尝试之间的区别
#!/usr/bin/env bash
dir=/tmp/getlist.test/
mkdir -p "$dir"
cd "$dir"
touch 'file not starting foo' foo foobar barfoo 'foo with spaces'\
'foo with'$'\n'newline 'foo with trailing whitespace '
# while with process substitution, null terminated, empty IFS
getlist0() {
while IFS= read -d $'\0' -r file ; do
printf 'File found: '"'%s'"'\n' "$file"
done < <(find . -iname 'foo*' -print0)
}
# while with process substitution, null terminated, default IFS
getlist1() {
while read -d $'\0' -r file ; do
printf 'File found: '"'%s'"'\n' "$file"
done < <(find . -iname 'foo*' -print0)
}
# pipe to while, newline terminated
getlist2() {
find . -iname 'foo*' | while read -r file ; do
printf 'File found: '"'%s'"'\n' "$file"
done
}
# pipe to while, null terminated
getlist3() {
find . -iname 'foo*' -print0 | while read -d $'\0' -r file ; do
printf 'File found: '"'%s'"'\n' "$file"
done
}
# for loop over subshell results, newline terminated, default IFS
getlist4() {
for file in "$(find . -iname 'foo*')" ; do
printf 'File found: '"'%s'"'\n' "$file"
done
}
# for loop over subshell results, newline terminated, newline IFS
getlist5() {
IFS=$'\n'
for file in $(find . -iname 'foo*') ; do
printf 'File found: '"'%s'"'\n' "$file"
done
}
# see how they run
for n in {0..5} ; do
printf '\n\ngetlist%d:\n' $n
eval getlist$n
done
rm -rf "$dir"