OT: bash script - unexpected exit

Dave Ihnat dihnat at dminet.com
Mon Jan 16 22:10:45 UTC 2012


On Mon, Jan 16, 2012 at 09:25:30PM +0100, Andre Speelmans wrote:
> I was not trying, the OP had a script that did a:
> cat file | while read line; do something done
> 
> Matthew commented that you should not rely on cat for reading a file
> line by line and I was curious as to why not. ...

I'm not aware of any particular reason not to use 'cat', and while it
doesn't cost a lot, it's usually less expensive to use redirection.

I just wanted to remind people that another way to redirect input (and
output) is through the exec command.  For instance:

  exec 0</usr/tmp/foo
  exec 1>/usr/tmp/bar
  exec 2>/usr/tmp/error

  while read INLINE
  do
  	echo $INLINE
  done

would read lines from file "/usr/tmp/foo" and output them to
"/usr/tmp/bar", all within the shell.  Moreover, any errors (should be none
with something this simple, of course) would go to "/usr/tmp/error" as
STDOUT.

But wait!  There's more!

You can redirect to/from any numeric file descriptor.  For instance:

  exec 3</usr/tmp/foo

  while read INLINE <&3
  do
  	echo $INLINE
  done

would open file descriptor 3 on "/usr/tmp/foo", and the "while read" will
walk through that file line by line.

You can close descriptors in a script when done with them, e.g.,

  exec 3>&-

would close that descriptor opened in the above script snippet.

Cheers,
--
	Dave Ihnat
	dihnat at dminet.com


More information about the users mailing list