我正在尝试使 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/