Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 
share|improve this question
up vote 14 down vote accepted

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...

share|improve this answer
Thanks a lot : ) – Searock Oct 21 '10 at 16:43

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.

share|improve this answer

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.

share|improve this answer
cat < first > temp works just fine. – JanC Oct 20 '10 at 9:51

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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