-1

$ cat a.txt > a.txt

Why does this above command make a.txt empty?

Base on my understanding, cat a.txt is going to shows the a.txt, then write the output to a.txt. It should do nothing, but why a.txt become empty? Can someone please explain it? Thanks.

Derick Alangi
  • 1,080
  • 1
  • 11
  • 31
qi xu
  • 3
  • 2

1 Answers1

0

The redirect to stdout (>) takes precedence over any command. What this means is that the shell prepares the file that will get stdout first by zeroing it out. When you then run the cat command, it prints out an empty file.

This is why you never try to modify a file by redirecting a command to the same file it is being read from. You will always be processing an empty file.

Hope this helps.

Lewis M
  • 550
  • 3
  • 7