When you write the command wc -l < file1.txt > file1.txt
, your shell will first read the command as a whole and redirect the standard input, output from/to file1.txt
.
Then when a file is open for writing using >
, if a file exists it will be overwritten and an empty file is created. the process (your wc
) will then start its execution and it will write in it until the end of the execution.
Your wc -l
will however have to read the file and count the number of lines in it, as the file is empty (overwritten) it will just dump in it:
0 file1.txt
To prove this look at what happens in appending mode using >>
$ cat file1.txt
a
b
b
$ wc -l file1.txt
3 file1.txt
$ wc -l file1.txt >> file1.txt
$ cat file1.txt
a
b
b
3 file1.txt
Your file content is intact and wc
does properly read the number of lines before appending the result to the file.
Note:
In general, it is never recommended to write and read in the same file except if you know exactly what you are doing. Some commands have an inline
option to modify the file during the run of the command and it is highly recommended to use them, as the file will not be corrupted even if the command crash in the middle of the execution.