Ajax Ajax - 1 year ago 80
Bash Question

cat command: unexpected output

I tried the following command

$cat < text > text
is a non-empty file.
There was no output to stdout and the file
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!
is a copy of

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

Answer Source

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