Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
2  
Try putting echo in front, then you'll see what the command really looks like. echo wc -l `ls` –  frostschutz Feb 8 '13 at 23:08
add comment

1 Answer 1

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 \[?*).

share|improve this answer
    
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. –  Stéphane Chazelas 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. –  Steve Kemp 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 -- * –  frostschutz 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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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