crazyeyes
crazyeyes

Reputation: 53

unix shell cat a >> a doesn't work

I would like copy the contents of a file twice on terminal,
but I don't generates same files,
so I type cat a >> a and this job doesn't stop,
I kill the job and open file a and found contents of a file a have many row...
I know cat a > b ; cat a >> b is work,
but I wonder why this code ( cat a >> a ) is not working ?
Please tell me what happen if anybody knows my problem.

thanks.

Upvotes: 0

Views: 1511

Answers (3)

Onlyjob
Onlyjob

Reputation: 5878

Here is correct way to do what you want:

echo "$(cat a)" >>a

Because cat reads and writes at the same time (so you can cat very big files) we need to capture the output before appending it to the "a" file...

Upvotes: 0

sth
sth

Reputation: 229663

While cat is reading lines from the beginning of the file, those lines are already being appended to the end of the file by >> a.

When cat reaches the the former end of the file it is not the end anymore. New lines have already been appended, and cat continues to read those lines. Those lines will also be appended by >> a and later be read by cat and appended again and read again and so on until you abort the process or run out of disk space.

Upvotes: 1

unxnut
unxnut

Reputation: 8839

cat a >> a will not work because you have opened file a for both read and append. You keep on reading a file to which you are adding more data, never reaching the end of file.

Upvotes: 3

Related Questions