4

For example:

myCleanVar=$( wc -l < myFile )
myDirtVar=$( wc -l myFile )

echo $myCleanVar
9

echo $myDirtVar
9 myFile

why in "myCleanVar" I get an "integer" value from the "wc" command and in "myDirtVar" I get something like as: "9 file.txt"? I quoted "integer" because in know that in Bash shell by default all is treated as a string, but can't understand the differences of the behaviour of first and second expression. What is the particular effect of the redirection "<" in this case?

shogitai
  • 1,823
  • 1
  • 23
  • 50

2 Answers2

5

The man page for wc says:

NAME

   wc - print newline, word, and byte counts for each file

SYNOPSIS

   wc [OPTION]... [FILE]...
   wc [OPTION]... --files0-from=F

DESCRIPTION

Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified.

So when you pass the file as an argument it will also print the name of the file because you could pass more than one file to wc for it to count lines, so you know which file has that line count. Of course when you use the stdin instead it does not know the name of the file so it doesn't print it.

Example

$ wc -l FILE1 FILE2
  2 FILE1
  4 FILE2
  6 total
Community
  • 1
  • 1
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
5

wc will list by default the name of file allowing you to use it on more than one file (and have result for all of them). If no filename is specified, the "standard input", which is usually the console input, is used, and no file name is printed. The < is needed to specify an "input redirection", that is read the input from given file instead of using user input.

Put all this information together and you get the reason of wc's behavior in your example

Question time: what would be the output of cat file | wc -l ?

pqnet
  • 6,070
  • 1
  • 30
  • 51
  • Thank you! You right, the redirection < "deceives" the wc that the content of the file is put by keyboard. In simpler words: the input redirection "removes" the fileName, so wc doesn't have any fileName to print. With < the wc sucks. Well, I'm thinking to do a t-shirt with "With < the wc sucks." on Spreadshirt! :P – shogitai Aug 18 '14 at 16:36