head behaviour

Dag-Erling Smørgrav des at des.no
Sun Jun 6 14:35:20 UTC 2010


Doug Barton <dougb at FreeBSD.org> writes:
> Bakul Shah <bakul at bitblocks.com> writes:
> > $ ps|(head -1; grep sh)
> >    PID  TT  STAT      TIME COMMAND
> I don't understand why you think this would work. There is no input to
> the grep command. The only reason it exits at all is that you are
> executing in a subshell.

The output from ps is piped to the subshell, so all processes within
that subshell get their stdin from that output.

Bakul's error is in assuming that head will *consume* only the first
line of input, whereas the only guarantee actually given is that it will
*print* only the first line of input.

This particular one-liner can be implemented reliably as follows:

% ps | (read header; echo $header; grep sh)
PID  TT  STAT      TIME COMMAND
 3415   0  Ss     0:00.31 -zsh (zsh)
 3476   0  S+     0:00.00 -zsh (zsh)

because read is a shell built-in, and the shell guarantees that it will
not consume more input than necessary.

DES
-- 
Dag-Erling Smørgrav - des at des.no


More information about the freebsd-hackers mailing list