in linux terminal,
$ echo hi > foo
$ wc foo > foo
$ cat foo
0 0 0 foo (Output)
$
But if
$ echo hi >foo
$ wc foo
1 1 3 foo (Output)
$
Why these outputs are different?
in linux terminal,
$ echo hi > foo
$ wc foo > foo
$ cat foo
0 0 0 foo (Output)
$
But if
$ echo hi >foo
$ wc foo
1 1 3 foo (Output)
$
Why these outputs are different?
When you redirect output to a file, the file is first emptied. So the file doesn't contain anything in it when wc
tries to read it.
In general, you shouldn't try to use the same file as input and output, it will almost never work.
As Barmar said in his answer the ' > ' Symbol empties the file before writing the new data to the file to which output is being redirected. so what you are essentially doing is using wc on an emptied file.
Instead of truncating the output you can append (' >> ') the output using the following code :
$ wc foo >> foo
$ cat foo
hi
1 1 3 foo
To get a more deep understanding on I/O Redirection in Linux follow the following article which covers the topic in detail.