符合POSIX标准的外壳相当于Bash "while read -d $'' ..."?



我正试图使Bash脚本严格符合POSIX,即通过使用checkbashisms -px ${script_filename}来消除任何潜在的"Bashmism"。在给定的文件中,我使用find遍历一个目录,然后使用-print0将每个文件路径管道传输到read,使用作为分隔符,以便能够处理包含换行符的文件名:

find . -print0 | while read -d $'' inpath
do
echo "Reading path "${inpath}"."
done

然而,checkbashisms不喜欢这样,因为选项-d不严格符合POSIX:

可能的抨击。。。第n行(使用-r以外的选项读取)

如何编写符合POSIX的等效代码,即使用非换行符读取find的输出?

如果没有-d选项,read内置无法读取以null结尾的数据。

您可以在find + xargs:中执行此操作

find . -mindepth 1 -print0 | xargs -0 sh -c 'for f; do echo "Reading path "$f""; done' _

或者,如果你不介意为每个文件生成一个shell,只需使用find:

find . -mindepth 1 -exec sh -c 'echo "Reading path "$1""' - {} ;

最新更新