dylanaraps / pure-sh-bible

📖 A collection of pure POSIX sh alternatives to external processes.
MIT License
6.45k stars 281 forks source link

read multi-line string with Process Substitution #52

Closed georgalis closed 8 months ago

georgalis commented 8 months ago

I would like to read a multi-line string, with proper exit code. Here Document, and Here String methods are not optimal, for performance, Process Substitution is desired, eg

read -d "" lines < <(printf "one \ntwo \nthree \n")

"works" however the trailing \n is missing from the string and it returns a signal 1

The following reads the string as expected, with an exit status 0

eot="$(awk 'BEGIN{printf "%c",4}')"
IFS= read -d "$eot" lines < <(printf "one \ntwo \nthree \n${eot}")
echo "$lines"
one
two
three

using GNU bash, version 5.2.15(1)-release is it possible to read a multi line string with Process Substitution and correct exit status?

andry81 commented 8 months ago

@georgalis

IFS= read -d "$eot" lines < <(printf "one \ntwo \nthree \n${eot}") using GNU bash, version 5.2.15(1)-release is it possible to read a multi line string with Process Substitution and correct exit status?

 IFS= read -d '' -r lines < <(printf "one \ntwo \nthree \n")

Why not this?

georgalis commented 8 months ago

@georgalis

IFS= read -d "$eot" lines < <(printf "one \ntwo \nthree \n${eot}") using GNU bash, version 5.2.15(1)-release is it possible to read a multi line string with Process Substitution and correct exit status?

 IFS= read -d '' -r lines < <(printf "one \ntwo \nthree \n")

Why not this?

@andry81 thanks for your reply, that does not exit clean, here is an example...

IFS= read -d '' -r lines < <(printf "one \ntwo \nthree \n") && echo success || echo error

this was inadvertently posted in the wrong repo! closing here and reopening in pure-bash-bible https://github.com/dylanaraps/pure-bash-bible/issues/144 ...didn't know about this repo, though I appreciate it for reference, to keep my sh code sh clean!

Out of curiosity, where can we find sh on modern operating systems? Please reply here with respective reference!

from NetBSD man sh

HISTORY
     A sh command appeared in Version 1 AT&T UNIX.  It was replaced in
     Version 7 AT&T UNIX with a version that introduced the basis of the
     current syntax.  That was, however, unmaintainable so we wrote this one.
     This NetBSD sh is a much modified descendant of the ash shell written by
     Ken Almquist.