11

Normally we use a different file to redirect the output.

For example :

cat < first > temp

In this command the contents of first are redirected to temp instead of the standard output.

Then why does it truncates the file if I use the same file name?

Why can't it overwrite the same file?

cat < first > first 
19

When you use I/O redirection like that, both the "input" & "output" file are opened by the shell before the command is executed. And opening a file for overwriting is the same as truncating it before writing. The result: cat sees an empty file on input...

0

Because handling it in the general case would be very complicated. Just consider the following example:

A program reads a file line by line and outputs each line twice. Now for this to work without a second file (ie on the same file) the program would need to buffer most (all) of the lines which it will read, since they will be overwritten otherwise before they can be read.

To keep matters simple programs usually use a secondary, temporary file which they move over the original once they are finished. This is for example how sed -i (inline) works.

0

Typically the syntax for redirecting in this is case should be cat first > temp. This means that cat's output of first is sent to the file of temp. In the case of your statement cat < first > temp, the output cat has not been completed at the time it is redirected to out again. Nothing in results in nothing out.

However cating a file and the output redirected to another file is no different than a basic cp.

  • cat < first > temp works just fine. – JanC Oct 20 '10 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.