1

I'm testing basic bash command on Ubuntu, when I put on terminal

wc -l < file1.txt > file2.txt 

all lines from file1 are read by wc and the number is saved to file2.txt.

However if I use the similar command wc -l < file1.txt > file1.txt but I try to save it in the same > file1 the output is always 0.

What is the reason of this behavior ?

Allan
  • 12,117
  • 3
  • 27
  • 51
axel_87
  • 37
  • 6

3 Answers3

2

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.

Allan
  • 12,117
  • 3
  • 27
  • 51
0

Its because redirections have higher priority than other commands. Here the file1 will be emptied before any operations can be performed on it

Anirudh Simha
  • 340
  • 1
  • 8
  • 1
    Redirections aren't commands at all; they are part *of* a command, but it is true that they are processed by the shell before the command is run. – chepner Mar 18 '19 at 13:06
0

Try >> on file1.txt instead of >. >> will append to file unlike > overwriting whole file. Try -

    wc -l < file1.txt >> file1.txt
ViKiG
  • 764
  • 9
  • 21