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?

1
  • 1
    Why don't you try them both directly in the shell, to observe the behaviour directly? Aug 17, 2014 at 10:37

2 Answers 2

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 ?

1
  • 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, 2014 at 16:36
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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