Reputation: 8105
What does this command do cat t.txt >> t.txt
? let say the t.txt only have one line of text "abc123". I assume the output of "abc123" is appended to t.txt. So, I should have 2 lines of "abc123". However, it just going in to a infinite loop. It doesn't stop until I hit Control-C. Is this the expect behavior of >>?
Upvotes: 0
Views: 554
Reputation: 22925
cat
program opens the file for reading, reads the file and writes to standard out.
>>
is a shell append redirect.
What you are seeing is the following cycle:
cat
reads a line from t.txt
cat
prints the line to filet.txt
cat
tests if it is at the end of the file That 4th step will always be false, because by the time the EOF check happens a new line has been written. cat
waits because the write always happens first.
If you want to prevent that behavior, you can add a buffer in between:
$ cat t.txt | cat >> t.txt
In this way, the write occurs after cat t.txt
checks for EOF
Upvotes: 4
Reputation: 44444
What you are trying to do by:
cat t.txt >> t.txt
is like telling your system to read t.txt
line by line and append each line to t.txt
. Or in better words, "append the file to itself". The file is being gradually filled up with repetitions of the original contents of the file -- the reason behind your infinite loop.
Generally speaking, try to stay away from reading and writing to the same file using redirections. Is it not possible to break this down to two steps -- 1. Read from file, output to a temporary file 2. append to the temporary file to the original file?
Upvotes: 2
Reputation: 7946
cat
is a command in unix-like systems that concatenates multiple input files and sends their result to the standard output. If only one file is specified, it just outputs that one file. The >>
part redirects the output to the given file name, in your case t.txt.
But what you have says, overwrite t.txt with the contents of itself. I don't think this behavior is defined, and so I'm not surprised that you have an infinite loop!
Upvotes: 0