0

I am baffled by this example:

[ziga@brane ~]$ touch test.txt
[ziga@brane ~]$ echo "TEST" > test.txt
[ziga@brane ~]$ cat test.txt
TEST
[ziga@brane ~]$ cat test.txt | grep "TEST"
TEST
[ziga@brane ~]$ cat test.txt | grep "TEST" > test.txt
[ziga@brane ~]$ cat test.txt
[ziga@brane ~]$

Why does cat test.txt | grep "TEST" > test.txt delete contents of a file test.txt? I thought that > rewrites and >> appends! What am I missing?

71GA
  • 1,106

1 Answers1

1

because redirection happens first >test.txt so it truncate the file at very first, next cat test.txt read nothing and nothing pass to | grep "TEST" and so then nothing matches and finally nothing writes to opened file test.txt

αғsнιη
  • 41,407