1

Can anyone explain to me how does this command work.

wc -l `ls`

while this command gives the total number of java lines or txt lines.

1
  • 2
    Try putting echo in front, then you'll see what the command really looks like. echo wc -l `ls` Feb 8 '13 at 23:08
2

ls outputs a list of file/directory names in the current directory.

`ls` will be replaced by the output of ls. So you're actually running something like:

wc -l file1 file2 file3 ... fileN

And of course wc will open each file named in the command line in turn, to count the lines.

The same effect could be had by running:

wc -l *

Note that this only holds if none of the file names in the current directory contain any “weird” character (whitespace or \[?*).

4
  • If `ls` were replaced by the output of ls, then wc would be asked to count the lines of one file whose (long and multi-line) name is the output of ls. `ls` expands to the output of ls minus the trailing newline characters, and is then split into several words (by default on spc, tab and newline characters) and then each word is subject to globbing. It is only equivalent to wc -l * is the special case where no file name in the current directory contain spc, tab, newline, *, ? or [ characters. Using ls that way is just plain wrong. Feb 8 '13 at 22:03
  • 1
    I could have been more specific; but yes the shell will split the output from ls into tokens, based on IFS. etc. Regardless, as you say, using ls like this is weird at best, and dangerous at worst.
    – user28151
    Feb 8 '13 at 22:49
  • The note should go above the * as * is not affected by whitespace or special characters. With the exception of files starting with -, which may be interpreted by wc as an option. workaround wc -l -- * Feb 8 '13 at 23:11
  • 1
    See also partmaps.org/era/unix/award.html#ls on this "Useless (and Sometimes Dangerous) Use of ls"
    – tripleee
    Feb 9 '13 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.