I'm developing a program in ncurses that will read from stdin, however, while checking how some other programs do this, I noticed that it's not consistent. For instance, the following two work fine

tail file.txt | cat
tail file.txt | cat -

While these won't work unless I use -:

cat file.txt | vim
cat file.txt | file

Is there a reason why some programs allow piping data without - and some don't? Should they support both ways?

  • 2
    It likely depends on whether the program in question is normally expected to work in pipe. Both vim and file do not normally participate in pipes. So you need to ask yourself, is my program expected to live in a pipe, or not? – Stephen Rauch Feb 19 '17 at 16:30
  • That makes sense and probably answers the question. Thanks. – Darren Feb 19 '17 at 16:39

Programs that are meant to act as stream filters, taking data from some input source and progressively processing it and producing output, normally read from standard input when invoked with no non-option arguments. So for example cat, tail, etc. read from standard input by default. Tools like grep, sed, etc. require one operand (the regexp for grep, the script for sed) and read from standard input if that's the sole operand. Vi(m) does not fit this mold: it's an interactive program, not a stream filter, so it starts in interactive mode when you pass no argument.

file is an exception: it doesn't read from stdin unless stdin is given as an argument (possibly through the syntax -). I don't know why neither the original author nor the POSIX committee decided that it wouldn't read from stdin. This may be because file cares not only about file contents, but also about file types — file foo reports whether foo is a directory, a regular file, a symbolic link, etc. So it isn't quite a stream filter like the others, even though it's usually used as such. It's halfway between grep (a stream filter) and ls (which cares only about the file as a directory entry and not at all about the file contents).

(grep -r does care about file types as well, but that's an addition that came much later than the original command.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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