Ajax Ajax - 7 months ago 32
Bash Question

cat command: unexpected output

I tried the following command

$cat < text > text
where
text
is a non-empty file.
There was no output to stdout and the file
text
became blank. I expected cat command to read the file text and output the contents to the same file.

However when I try
$cat < text > newtext
it works!
newtext
is a copy of
text
.

Another doubt, When I try
$cat < text >>text
where
>>
usually appends to a file. My terminal gets stuck in an infinite loop and file
text
is repeatedly appended to itself. Why does this happen?

Answer

You cannot use the same file as stdin and stdout. Why? Because all commands are executed at the same time, and the shell prepares redirections before executing the commands. Hence, the output file is emptied before executing.

Instead, you have to use temporary files.

A workaround could be your solution or also:

cat text > newtext && mv newtext text