read stdin into variable?

Wolf wolf at wolfsden.cz
Sun Nov 8 22:35:50 UTC 2020


On 2020-11-08 21:41:51 +0000, Harald van Dijk wrote:
> 
> There are two good workarounds. One is yours, which ensures read a b is not
> executed in a subshell environment. Depending on the use case, another good
> alternative is
> 
> echo 12 34 | {
>   read a b
>   echo "'${a}''${b}'"
> }
> 
> This still executes `read a b` in a subshell environment, but lets the
> following commands that use $a and $b also execute in that same subshell
> environment. This workaround can be used when the following commands do not
> need to read from the original stdin.

If the original stdin is needed, exec can be used. As in (the echo 1 2 is
supposed to simulate "the original stdin"):

echo 1 2 | {
	exec 3<&0
	echo 3 4 | {
		read a b
		printf '%s %s\n' "$a" "$b"
		read a b <&3
		printf '%s %s\n' "$a" "$b"
	}
}

But yes, this has the potential to get bit confusing fairly quickly.

Have a nice day,

W.

-- 
There are only two hard things in Computer Science:
cache invalidation, naming things and off-by-one errors.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://lists.busybox.net/pipermail/busybox/attachments/20201108/c872e914/attachment.asc>


More information about the busybox mailing list