coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

standard for stdin / args handling?


From: Aaron Davies
Subject: standard for stdin / args handling?
Date: Wed, 26 Dec 2012 16:18:36 -0500

afaict from my general *nx experience, the basic rule for text-handling 
utilities (filters, etc.) is as follows: first, no argument(s) means stdin is 
used; second, argument(s) means stdin is ignored, unless "-" is present as an 
argument, in which case stdin is used in the position in the sequence where the 
first "-" occurs (later "-"s have no effect, presumably due to the way pipes 
behave); finally, if no arguments and not receiving a pipe and in some sort of 
interactive context (stdin is a tty?), stdin is accepted from the terminal (and 
handled line-by-line (rev(1)) or at end-of-file (tac(1)), as appropriate).

cat(1) is the canonical example.

my questions are: have i described the behavior correctly, and is there 
anything (in any context--C, shell, etc.) to make creating new tools which 
follow these rules easier?

for instance, in a small filter i recently wrote in C (which only accepts a 
single file (or stdin)), i have this (simplified):

   FILE *f;
   argp_parse(&argp,argc,argv,0,NULL,&arguments);
   // read arg or stdin
   if(!strcmp(arguments.arg,"-"))
       f=stdin;
   else
       if(!(f=fopen(arguments.arg,"r")))
           error(1,errno,"%s",arguments.arg);

and in a (ksh) shell filter, this:

   (($#)) && files=("$@") || files=(-)
   integer n=${#files[*]} i=0
   for ((i=0;i<n;i++))
   do
       file=${files[$i]}
       sed -rn "/$pattern/,$ p" "$file"
   done

note that here, i'm relying on sed's ability to correctly interpret a file 
argument of "-" -- if i wanted to do the reading myself (e.g. using "<") or to 
use a utility that didn't understand "-", i'd have to do something more 
sophisticated.

both of these seem somewhat overcomplicated, and are likely to have bugs 
lurking in them. is there a better way to do this?
-- 
Aaron Davies
address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]