3

In bash, if I wanted to read, say 3, characters from a pipe, I could do:

... | read -n3

In zsh's read, the closest option seems to be -k:

-k [ num ]
Read only one (or num) characters. All are assigned to the first name, without word splitting. This flag is ignored when -q is present. Input is read from the terminal unless one of -u or -p is present. This option may also be used within zle widgets.

Note that despite the mnemonic ‘key’ this option does read full characters, which may consist of multiple bytes if the option MULTIBYTE is set.

And for -u and -p:

-u n
Input is read from file descriptor n.

-p
Input is read from the coprocess.

A bare echo foobar | (read -k3; echo $REPLY) hangs waiting for input. -p fails with read: -p: no coprocess. Only the following works:

echo foobar | (read -k3 -u0; echo $REPLY)

This is the first time I'm seeing something that's more difficult to achieve in zsh than in bash.

Is there a simpler way to read N characters from stdin (whatever that might be) than this?

0

It works for me without the subshell:

% echo foobar | read -k3 -u0; echo $REPLY
foo
% echo $ZSH_VERSION
5.5.1
  • The subshell is mostly irrelevant. The point is the extra options needed, and the need to specify the file descriptor. – muru Jun 27 '18 at 7:47
  • I do find it interesting that help read makes no mention of reading from /dev/tty. – Tom Hale Jun 27 '18 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.