[comp.unix.questions] Detecting pipe closure in shell script

cl@datlog.co.uk (Charles Lambert) (01/15/88)

I have a shell script with the following fragment in it:

    | tee $TFILE | more

If I quit more(1) before output from tee(1) is complete, I want to
scrap $TFILE,  else I want to move it to another name.  I've tried

    | ( trap 'rm $TFILE' 13; tee ) | more;
    mv $TFILE othername

and

    | ( tee ; mv $TFILE othername) | more

but in both cases the move occurs regardless of completion (in the second
case, the "mv" seems to be executing even after shell script has exited).

Any smart tricks?

----------------------
Charles Lambert

hitz@mips.UUCP (David Hitz) (01/16/88)

In article <380@dlhpedg.co.uk> cl@datlog.co.uk (Charles Lambert) writes:
>I have a shell script with the following fragment in it:
>
>    | tee $TFILE | more
>
>If I quit more(1) before output from tee(1) is complete, I want to
>scrap $TFILE,  else I want to move it to another name.  I've tried
...
>Charles Lambert

Try

	| (tee "$TMP" && mv "$TMP" "$REAL" || rm "$TMP" ) | more

If the more dies, then the tee fails because it cannot finish its 
writes.  Note that the code above also has the effect of removing
the $TMP file if the mv failes.
-- 
Dave Hitz
UUCP: {decvax,ucbvax,ihnp4}!decwrl!mips!hitz 	DDD: hitz@408-991-0345

scl@virginia.acc.virginia.edu (Steve Losen) (01/18/88)

In article <380@dlhpedg.co.uk> cl@datlog.co.uk (Charles Lambert) writes:
>I have a shell script with the following fragment in it:
>
>    | tee $TFILE | more
>
>If I quit more(1) before output from tee(1) is complete, I want to
>scrap $TFILE,  else I want to move it to another name.  I've tried

Try this in the bourne shell:

... | 
if tee $TFILE; then
	mv $TFILE newname
else
	rm $TFILE
fi | more

If you quit out of more, tee gets a SIGPIPE and a non-zero exit status,
causing the "else" arm of the conditional to be executed.  Note that in
/bin/sh you can pipe into and out of if, while, for, and case statements.

If you don't mind destroying the file "newname" when you quit out of more,
use this simpler solution:

... | (tee newname || rm newname) | more

in /bin/sh "||" and "&&" have short-circuit evaluation, so you can
conditionally execute commands based on the exit status of a previous
command.

-- 
Steve Losen     scl@virginia.edu
University of Virginia Academic Computing Center