Ubuntu – Why does redirection to the same file truncate the file

bashcommand line

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 

Best Answer

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