问题描述
我正在尝试使Bash脚本严格符合POSIX,即使用checkbashisms -px ${script_filename}
删除任何可能的"Bashisms"。在给定的文件中,我使用find
遍历目录,然后使用
作为分隔符使用-print0
将每个文件路径通过管道传输到read
,以便能够处理包含换行符的文件名:
find . -print0 | while read -d $'' inpath
do
echo "Reading path "${inpath}"."
done
但是,checkbashisms
不喜欢这样,因为the option -d
isn't strictly POSIX-compliant:
可能存在的羞耻感……行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' _
或者,如果您不介意为每个文件生成一个外壳,只需使用find
:
find . -mindepth 1 -exec sh -c 'echo "Reading path "$1""' - {} ;