I have come across the command line wc < f1 f2
and it’s not clear for me what is happening under the hood:
$ echo -n 'a' > f1
$ wc f1
0 1 1 f1
$ echo -n 'bb' > f2
$ wc f2
0 1 2 f2
$ wc < f1 f2
0 1 2 f2
Here the standard input of wc
is being redirected to file f1
, but I’m also passing file f2
as argument. The output I get is as if I had typed wc f2
, i.e.., the standard input is not considered by wc
, it seems.
Is wc
discarding its standard input (wherever it points to) when it also gets passed a file as argument?
Is wc
internally still handling two file descriptors, one for standard input and another for the file it’s being passed as argument, or is it the kernel to "unplug" the standard input file descriptor from file f1
and plug it to file f2
later, in this case?
What else, or what IS actually happening, in a command line like wc < f1 f2
?
I am using the Bash shell in Ubuntu 22.04.
Thanks
2
Answers
wc < f1 f2
executeswc f2 <f1
– executes commandwc
with one argumentf2
and redirects filef1
to standard input.wc f2
just prints the counts for filef2
. Nothing happens to standard input.No, there is no "discarding", there is "ignoring".
wc
does not touch standard input at all. "Discarding" would imply the standard input is fully read afterwc
exits, but it is not.No,
wc
is "handling" onlyf2
file – opening and reading it. You can see what system callswc
is doing by usingstrace wc f2
.There is no "unplugging".
Ignoring
stdin
if file arguments are specified is normal behavior for many commands. This is done by the program itself, i.e. by thewc
program in this case.Often you can use
-
as a command line argument to usestdin
like an ordinary file specified on the command line.This behavior is defined by the POSIX specification for
wc
. My understanding is that it’s implementation-dependant if-
is treated as meaning standard input.Citing https://man7.org/linux/man-pages/man1/wc.1p.html
Example: