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.
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.
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.
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