linuxshellwc

wc command with no FILE argument (reading from standard input)


Regarding 'wc' (word count) command... I am trying to understand the following (from 'man wc' which I have quoted below) "With no FILE, or when FILE is -, read standard input."

How exactly does this work? At what point do I type the "standard input"?

Finding explanations online rather confusing. Maybe I am just missing some basic info regarding what exactly stdin is.

From 'man wc'

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. A word is a non-zero-length sequence of characters delimited by white space.

   With no FILE, or when FILE is -, read standard input.

Solution

  • Quoting man 3 stdin:

           Under  normal circumstances every UNIX program has three streams opened
           for it when it starts up, one for input, one for output,  and  one  for
           printing diagnostic or error messages.  These are typically attached to
           the user's terminal (see tty(4)) but might instead refer  to  files  or
           other  devices,  depending  on what the parent process chose to set up.
           (See also the "Redirection" section of sh(1).)
    
           The input stream is referred to as "standard input"; the output  stream
           is  referred  to as "standard output"; and the error stream is referred
           to as "standard error".  These terms are abbreviated to form  the  sym‐
           bols used to refer to these files, namely stdin, stdout, and stderr.
    

    so basically when you type wc it is waiting for input, for example you can type bla followed by Ctrl+d and wc will terminate and print the stats:

    wc
    bla
          1       1       4
    

    same result as:

    echo 'bla' | wc 
          1       1       4
    

    in this case stdout of echo command is sent to stdin of wc

    from man 7 pipe:

           pipe()  creates  a pipe, a unidirectional data channel that can be used
           for interprocess communication. Data  written  to  the write end of the pipe is buffered by the
           kernel until it is read from the read end of the pipe.