[comp.lang.perl] Piping into Shell scripts

lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) (02/28/90)

In article <2283@syma.sussex.ac.uk> andy@syma.sussex.ac.uk (Andy Clews) writes:
: Is there any way of getting a Shell script (C or Bourne) to recognise
: whether it is receiving input from a pipe?

Sort of.

: My script includes something like this:
: 
: 	echo "Please enter message text and then enter a CTRL D"
: 	cat > foo
: 	etc.etc.
: 
: In some circumstances I might want to pipe text into the script, so I
: don't want it to echo the prompt message.  I have RTFM (hope I haven't
: missed something)...

You don't hope you didn't miss something, you hope you DID miss something.
Fortunately you did.

To do what you want (as opposed to what you asked for), say

	test -t 0 && echo "Please enter message text and then enter a CTRL D"

This will echo the message only if stdin is attached to a terminal.

To do what what you asked for (determine if it's a pipe) would take
a C program or a Perl script.  On a BSD system, where a pipe is a kind of
socket, you could say
	
	perl -e 'exit -S STDIN;' && echo "My prompt"

On a Sun (and probably AT&T systems) it's considered a FIFO, so you'd say

	perl -e 'exit -p STDIN;' && echo "My prompt"

Of course, why start an extra process?  Here's a portable version, and
you won't have to worry about how to suppress the newline on the prompt:

	perl -e 'print "My prompt" unless -S STDIN || -p STDIN;'

And, since you wanted -t anyway, just say:

	perl -e 'print "My prompt" if -t;'

I will refrain from suggesting that you write the whole script in Perl.  :-)

Larry Wall
lwall@jpl-devvax.jpl.nasa.gov