How to send output to both screen and mail?

12,047

The easiest way is probably to tee the message to stderr as well as stdout:

echo "Script finished on date" | tee /dev/stderr \
    | /usr/bin/Mail -s "Script complete" "[email protected]"

tee duplicates its input to multiple destinations, including stdout. By default, both stderr and stdout go to the screen; you're redirecting stdout to Mail, leaving just stderr going to the screen.

If you need it in stdout for some reason, you could redirect it back using a subshell (or several other ways):

(
    echo "Script finished on date" | tee /dev/stderr \
        | /usr/bin/Mail -s "Script complete" "[email protected]"
) 2>&1
Share:
12,047
sammy
Author by

sammy

Updated on September 18, 2022

Comments

  • sammy
    sammy over 1 year

    I use the following to send an email at the end of a script.

    echo "Script finished on `date`" | /usr/bin/Mail -s "Script complete" "[email protected]".
    

    However, I want to echo the same message onto the screen as well. How do I do that in the same statement?

  • Alessio
    Alessio over 11 years
    alternatively, tee to a file and then mail the file...very useful if the output is huge and you want to send it, e.g., as a base64-encoded gzipped MIME attachment. or just redirect all output to a file (e.g. with exec &> $LOGFILE) and then restore stdout, cat the file to stdout and mail it.
  • sammy
    sammy over 11 years
    Thank you Craig. Since my text in this case is very small, I will go with the response from derobert.
  • sammy
    sammy over 11 years
    Hmm.. this did work however I realized that I needed to add more to my problem description. I used this solution as the last line of my script. I used a "nohup" command on my script to collect all the output of my script as "nohup.out" and all I see is just this one line "Script finished on xxxxx". Prior to using this solution, I got all the script output fine. Is there a way how I can append the output of this last one line instead of erasing it all?
  • sammy
    sammy over 11 years
    Using "tee -a" solved the problem.