Pipe the output from three echo statement to mail

29,362

Solution 1

Your requirement is not completely clear, but try this

{
    echo "Total items: `echo $QUERY1 | awk '{print $1}'`"
    echo "Total Error: `echo $QUERY1 | awk '{print $2}'`"
    echo "Percentage: $QUERY2"
} | mail -s "subject" [email protected],[email protected]

The { .. } pair creates a process group, and all std-output is redirected into the 1 | (pipe), which connects to the std-in of your mail program.

You may need to use mailx, -s specifies subject, which I see from your other question on this topic that you seem to understand.

Also sendmail will need to be running and properly configured for any mail to be delivered from the machine that you execute this script.

IHTH


Edit: 2015-11-07

Just got a 'nice answer' star for this, and on on review, I'm surprised that I didn't comment on excessive use of processes. For this case, this can be reduced to one call to awk, i.e.

awk -v q1="$QUERY1" -v q2="$QUERY2" \
 'END {
    split(q1,q1arr)
    print "Total items: " q1arr[1] \
          "Total Error: " q1arr[2] \
          "Percentage: " q2
}' /dev/null \
| mail -s "subject" [email protected],[email protected]

Or for the one-liner crowd ;-), that is

awk -v q1="$QUERY1" -v q2="$QUERY2" 'END {split(q1,q1arr);print "Total items: " q1arr[1] "\nTotal Error: " q1arr[2] "\nPercentage: " q2 }' /dev/null | mail -s "subject" [email protected],[email protected]

The { .. } aren't needed in this case, as there is only one process connecting to the pipe.

For a case like a summary report being sent once a day, the original code is completely usable (but non-optimal). However, coding non-optimally leads to bad habits. Calling 5 processes when one will suffice in a loop that runs 1000s of times in a day, will consume compute resources unnecessarily.

Finally, as the o.p. didn't include any sample data, the code is only lightly tested.

Solution 2

Just create a function in bash and | (pipe) it to sendmail.

            #!/bin/bash

            echo_statement(){

            echo "Total items: `echo $QUERY1 | awk '{print $1}'`"
            echo "Total Error: `echo $QUERY1 | awk '{print $2}'`"
            echo "Percentage: $QUERY2"

            }
            echo_statement | mail -s "subject" [email protected]
Share:
29,362
AKIWEB
Author by

AKIWEB

Updated on November 09, 2020

Comments

  • AKIWEB
    AKIWEB over 3 years
    echo "Total items: `echo $QUERY1 | awk '{print $1}'`"
    echo "Total Error: `echo $QUERY1 | awk '{print $2}'`"
    echo "Percentage: $QUERY2"
    

    How can I send these three things in a single email using mail command. So the mail body should be like this below whenever I get any email, in each line there should be one echo statement-

    Total items:-    Some Number
    Total Error:-   Some Number
    Percentage:-   Some Number
    

    I am running SunOS

    bash-3.00$ uname -a 
    SunOS lvsaishdc3in0001 5.10 Generic_142901-02 i86pc i386 i86pc