From owner-freebsd-hackers@FreeBSD.ORG Sat Jun 5 20:12:43 2010 Return-Path: Delivered-To: freebsd-hackers@freebsd.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:4f8:fff6::34]) by hub.freebsd.org (Postfix) with ESMTP id 7B195106564A for ; Sat, 5 Jun 2010 20:12:43 +0000 (UTC) (envelope-from bakul@bitblocks.com) Received: from mail.bitblocks.com (mail.bitblocks.com [64.142.15.60]) by mx1.freebsd.org (Postfix) with ESMTP id 679018FC13 for ; Sat, 5 Jun 2010 20:12:43 +0000 (UTC) Received: from bitblocks.com (localhost.bitblocks.com [127.0.0.1]) by mail.bitblocks.com (Postfix) with ESMTP id C79345B52 for ; Sat, 5 Jun 2010 13:12:42 -0700 (PDT) To: freebsd-hackers@freebsd.org Date: Sat, 05 Jun 2010 13:12:42 -0700 From: Bakul Shah Message-Id: <20100605201242.C79345B52@mail.bitblocks.com> Subject: head behaviour X-BeenThere: freebsd-hackers@freebsd.org X-Mailman-Version: 2.1.5 Precedence: list List-Id: Technical Discussions relating to FreeBSD List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Sat, 05 Jun 2010 20:12:43 -0000 Consider: $ yes | cat -n | (read a; echo $a; head -1) 1 y 2 y $ yes | cat -n | (head -1; read a; echo $a) 1 y 456 y As you can see, head reads far more than it should. This is fine most of the time but often it results in surprising output: # print ps header and all lines with sh in it $ ps|(head -1; grep sh) PID TT STAT TIME COMMAND # print first and last two lines $ look xa | (head -2; tail -2) xanthaline xanthamic Not quite what you expected, right? Yes, you can use read and echo N times but this is not as convenient as using head: $ look xa | (read a; echo $a; read a; echo $a; tail -2) xanthaline xanthamic xarque Xaverian The "fix" is to make sure head reads no more than $N bytes where $N is the number of *remaining* lines to be read. Yes this slows head down some but makes it more useful. [Ideally all commands that quit after partially reading their input ought to behave like this but that would slow down their common use far too much] Comments? Thanks to Rob Warnock for pointing out the head problem.