Monday, October 24, 2011

Of cats and redirection...

Let's say you want to cat a file and redirect the output to itself, something like:

cat file > file;

Or perhaps more usefully:

cat file | tail -n 100 > file;

You will end up with an empty file. This is likely because of how the shell handles inodes and redirection (just a guess). A quick and way to get around this is:

cat file | tail -n 100 | dd of=file;

And viola! file points at the correct inode.

2 comments:

  1. And of course, if you've been following along for a week or two, you know that this (BING!) is a Useless Use of Cat!

    Rememeber, nearly all cases where you have:

    cat file | some_command and its args ...

    you can rewrite it as:

    <file some_command and its args ...

    and in some cases, such as this one, you can move the filename
    to the arglist as in:

    some_command and its args ... file

    Just another Useless Use of Comment Form,

    kenno

    ReplyDelete
  2. More usefully, you could also redirect to a file and then copy the file over, though this feels kludgier:

    TMPFILE=$(mktemp $(basename $(pwd))); tail -100 $file >$TMPFILE && mv $TMPFILE $file

    ReplyDelete