Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSIX-compliant shell equivalent to Bash "while read -d $'\0' ..."?

I'm trying to make a Bash script strictly POSIX-compliant, i.e. removing any potential "Bashisms" by using checkbashisms -px ${script_filename}. In the given file, I walk through a directory using find and then pipe each file path to read using \0 as a delimiter by using -print0 in order to be able to handle filenames containing newline characters:

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

However, checkbashisms doesn't like this because the option -d isn't strictly POSIX-compliant:

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

How can I write equivalent code which is POSIX-compliant, i.e. to read output from find using a non-newline delimiter?

like image 895
errantlinguist Avatar asked May 20 '16 09:05

errantlinguist


1 Answers

Without -d option, read builtin cannot read null terminated data.

You can do this in find + xargs:

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

Or if you don't mind spawning a shell for each file use just find:

find . -mindepth 1 -exec sh -c 'echo "Reading path \"$1\""' - {} \;
like image 58
anubhava Avatar answered Nov 05 '22 02:11

anubhava