[comp.unix.questions] How to tell if you're in a pipe...

rbarrell@lgnp1.LS.COM (Robert Barrell) (06/22/89)

     [The machine through which I usually access the newsgroups had a bit of
a burp, so please forgive me if I'm repeating an answer, here.]  
  
     I don't know if it was ever answered, or not, but someone had asked about
how to determine if the program they were running was being used directly, or
in a pipe.  In glancing through the manuals, I happened to notice the isatty()
C call, and what it does, which prompted me to examine the "tty" shell command.
In doing so, I found that "tty" returns a 0 if standard-input is a terminal,
and returns a 1 if it isn't.  Also, with the "-s" option, "tty" can be made
silent, so the exit code may be used without having to redirect the output of
"tty" to /dev/null.  Thus, the following script will tell you if it is being
run in a pipe or not:  

     if [ `tty -s;echo $?` = 0 ]
     then
         echo "terminal"
     else
         echo "pipe"
     fi

     I hope this isn't to late (or already redundant) to be of use to the
person who originally asked the question.
------------------------------------------------------------------------------
     Robert Barrell
     "Hodgepodge" - Sysop of Milo's Meadow - A Citadel/UX BBS
     215-323-0497 - 300/1200/2400 - 24hrs. - login as "bbs"
------------------------------------------------------------------------------

maart@cs.vu.nl (Maarten Litmaath) (07/04/89)

rbarrell@lgnp1.LS.COM (Robert Barrell) writes:
\
\     if [ `tty -s;echo $?` = 0 ]
\     then
\         echo "terminal"
\     else
\         echo "pipe"
\     fi

What an `interesting' way to accomplish the following:

	if tty -s
	then
		echo terminal
	else
		echo pipe
	fi
or even
	tty -s && echo terminal || echo pipe
-- 
"I HATE arbitrary limits, especially when |Maarten Litmaath @ VU Amsterdam:
   they're small."  (Stephen Savitzky)    |maart@cs.vu.nl, mcvax!botter!maart