与POSIX兼容的外壳相当于Bash",而读-d$'

人气:794 发布:2022-10-16 标签: pipe shell bash find sh

问题描述

我正在尝试使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""' - {} ;

666