[clug] Next in my series of "how to do things in /bin/sh that you probably shouldn't".

Andrew Janke a.janke at gmail.com
Wed Aug 19 18:39:53 MDT 2009


Suppose that I want to send all output from a shell script to a
logfile as well as displaying it (within the script). To simply send
everything in a shell script I can just do this somewhere near the top
of the script:

   exec > logfile.txt 2>&1

But I am greedy, as such it is a pity you can't just do this:

   exec | tee logfile 2>&1

So instead the only way I know of doing this is as such:

#! /bin/sh

# set up
OPIPE=output.pipe
if [ ! -e $OPIPE ]; then mkfifo $OPIPE; fi
tee output.log < $OPIPE >&1 &
tpid=$!
exec > $OPIPE 2>&1


echo "here is where we do things $tpid"


# clean up
exec 1>&- 2>&-
wait $tpid
rm $OPIPE


Seems like an awful amount of work for a simple thing, anyone know a
better way?  Answers of "use python/perl/<some other language>" will
be dutifully ignored.

Thanks


--
Andrew Janke
(a.janke at gmail.com || http://a.janke.googlepages.com/)
Canberra->Australia    +61 (402) 700 883


More information about the linux mailing list