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
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...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.Typically the syntax for redirecting in this is case should be
cat first > temp
. This means thatcat
's output offirst
is sent to the file oftemp
. In the case of your statementcat < first > temp
, the outputcat
has not been completed at the time it is redirected to out again. Nothing in results in nothing out.However
cat
ing a file and the output redirected to another file is no different than a basiccp
.