0

I am learning shell scripting and i was stuck at sending an email. here in below code i am using conditions to check the files size if it is greater than 0 bytes then send an email.

if [ -s file1 ]
      printf "%s" "this is file1" | /usr/bin/mutt -s "test file" "ssunkara@mail.com" 

fi

if [ -s file2 ]
      printf "%s" "this is file2" | /usr/bin/mutt -s "test file" "ssunkara@mail.com" 

fi
if [ -s file3 ]
      printf "%s" "this is file3" | /usr/bin/mutt -s "test file" "ssunkara@mail.com" 

fi

as we can see i am using same code /usr/bin/mutt -s "test file" "ssunkara@mail.com" three times which i feel not a good coding. Is there any way that i can send the only one email with all the three messages in it.

ex: if all the three files are greater than zero bytes, i will receive 3 mails seperatly but instead i am looking to get only one mail like below.

this is file1
this is file2
this is file3
0

You could use the >> redirect to generate a temporary file first, then send the file:

out=$(mktemp /tmp/message.XXXXXXXX)
printf "%s" "this is file1" >> "$out"
printf "%s" "this is file2" >> "$out"
cat "$out" | mutt -s "test file" test@example.com
rm "$out"

Alternatively, it is possible to group multiple commands using { ...; } and pipe all of their output into the same process:

{
    if [ -s file1 ]
        printf "%s" "this is file1"
    fi
    if [ -s file2 ]
        printf "%s" "this is file2"
    fi
    if [ -s file3 ]
        printf "%s" "this is file3"
    fi
} | mutt -s "test file" test@example.com

Don't forget you can apply the | pipe to compound commands as well, e.g. the entire if...fi or for..in...done can be piped to another command:

for fname in file{1..3}; do
    if [ -s "$fname" ]; then
        printf "%s" "this is $fname"
    fi
done | mutt -s "test file" test@example.com
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.