1

I would like to know what the difference is between:

$ ls | wc -l

and

$ ls > foo
$ wc -l < foo

when counting all files in the current directorys. And why does the second one gives me one file more.

Florian Diesch
  • 86,013
  • 17
  • 224
  • 214
MassU
  • 11
  • 1
  • Parsing `ls` output is not a good way to count number of files, perhaps you should start using shell features for this kind of task.. – heemayl Nov 30 '15 at 01:25

2 Answers2

4

There is no difference, really. The second case would also include the file foo in the list and therefore gives you a count of 1 more.

kos
  • 35,535
  • 13
  • 101
  • 151
Doug Smythies
  • 14,898
  • 5
  • 40
  • 57
0

What you're doing with ls > foo is redirecting output of ls to a file. Surprisingly enough, the file is being created first, and included into the output of ls

   abcd:$ ls                                                                      
a?b  file name

abcd:$ ls > file                                                               

abcd:$ cat file
a
b
file
file name

Before redirection , there were two files a\nb and file name. After redirection : 3 files , file included. This is the real problem in your case.

But you probably noticed something else : why is a\nb file was listed on two lines. Why ? ls can list files, but shell allows almost any type of character in filename, including newline. Thus when output of ls is parsed, there may be erroneous information. For proper counting of files, which is what your main goal is here, you could use for loop with shell glob

abcd:$ for FILE in * ; do echo "1";done                                                                                               
1
1
1

As you can see it correctly shows i have 3 files (including the file redirected from before)

For more info , refer to http://www.dwheeler.com/essays/filenames-in-shell.html

Sergiy Kolodyazhnyy
  • 103,293
  • 19
  • 273
  • 492