Perplexed

Top Page
Attachments:
Message as email
+ (text/plain)
Delete this message
Reply to this message
Author: Kevin Buettner
Date:  
Subject: Perplexed
On Feb 28, 5:43pm, Michael Havens wrote:

> Well DUH! I know what you mean.... but isn't there an easier way to write the
> sorted file to the same file name (rather than renaming a tmp file)? If not I
> say that there should be!


Okay, here's an example of a way to avoid a rename. I wouldn't count
on this working in all shells and it's somewhat more difficult to
understand how it works.

    sort < testfile > `rm testfile ; echo testfile`


This counts on the fact that an open, but removed file will continue
to exist until it is closed. So the way that the above works is as
follows:

    1) testfile is opened for reading by the shell and assigned to file
       descriptor 0 (stdin).


    2) testfile is removed in the process of computing the name to use
       for the output redirection.  However, due to the fact that it's
       been opened, the contents of the file will not be deleted until
       the file descriptor opened in step 1 has been closed.


    3) A brand new file named "testfile" is opened (by the shell) for
       write access and assigned to file descriptor 1 (stdout).


    4) With stdin and stdout (file descriptors 0 and 1) set up as noted
       above, the "uniq" program runs, taking it's input from the old file
       named "testfile" and writing to the new one.  When uniq finishes,
       it will close stdin and stdout.  In the process, the kernel will
       free up the space associated with the original "testfile".


Note that this breaks down if the shell chooses compute the name for the
output file descriptor first. (If that happens, the file will be removed
before being opened for reading.) That's why I wouldn't count on it
working in all shells. It *did* work for me when I tried it using bash
a few minutes ago. There may be some versions of bash where it doesn't
work.

Kevin