bash - POSIX 兼容的 shell 相当于 Bash "while read -d $'\0' ..."?

标签 bash shell find pipe sh

我正在尝试使 Bash 脚本严格符合 POSIX 标准,即通过使用 checkbashisms -px ${script_filename} 删除任何潜在的“Bashisms” .在给定的文件中,我使用 find 遍历目录然后将每个文件路径通过管道传输到 read使用 \0使用 -print0 作为分隔符为了能够处理包含换行符的文件名:

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

然而, checkbashisms 不喜欢这个因为the option -d isn't strictly POSIX-compliant :

possible bashism in ... line n (read with option other than -r)

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

最佳答案

没有 -d 选项,read 内置函数无法读取空终止数据。

您可以在 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\""' - {} \;

关于bash - POSIX 兼容的 shell 相当于 Bash "while read -d $'\0' ..."?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37342833/

相关文章:

bash - 如何在 bash 中重定向嵌套函数调用的输出?

linux - 在文件中搜索一行并将下一个模式匹配的行替换为 linux 中的换行符(Shell 脚本)

fork 程序的 C++ shell 问题

linux - 如何压缩不符合特定条件的文件?

c++ - 在 vector 中查找 weak_ptr

python - 即使在重新启动 mac 终端后,我的 .bash_profile 更改也没有发生,我该怎么办?

找不到 bash 输出命令

linux - 编写一个 Makefile 以自动获取文件名并创建具有相同名称的相应可执行文件

bash - 在 bash 中退出管道

c - 在c中查找特定文件类型并保存