Putorius
Linux Quick Tips

Run a Command and Send the Output to an Email on Linux

Send Command Output as Email on Linux Command Line

In this quick tip we will discuss how to use the output of a script as the body of an email from the Linux command line. This is perfect for anyone wanting to run a command and send the output to an email address. Used with cron it can be an effective method for getting information about your system or specific application.

Install mailx

First you need a program capable of sending emails from the Linux command line. I have been using mailx for quite a few years and recommend it.

Installing mailx on Fedora, Red Hat, etc...

sudo dnf install mailx -y

On Red Hat 7 or older systems, you will still need to use yum.

sudo yum install mailx -y

Ubuntu, Mint, or other Debian based systems can use apt.

sudo apt install mailutils

Testing Your SMTP Service (Can you send mail?)

Before we begin, you MUST ensure your system is configured to send email. If you are sure it is, you can skip down. If you need to configure your system, then read "How to Send Mail Through ISP SMTP with Postfix".

To test the mail functionality of your system, simply send an email using our newly installed mailx program.

mailx -s "Test" my-email@my-domain.com < /etc/hosts

If your system is configured correctly, you will receive a copy of your hosts file in your email.

For more information on sending files read "Send file as an Attachment or Email Body from command Line".

Send the Output of a Command to an Email Address

Sending the output of a command is different that emailing an already established text file. You can't simply redirect or you will get a ambiguous redirect error.

[mcherisi@Fenrir ~]$ mailx -s "TEST" myemail@mydomain.com < $(cat /etc/hosts)
-bash: $(cat /etc/hosts): ambiguous redirect

The answer is to simply pipe the output of the command into the mailx command like so:

[mcherisi@Fenrir ~]$ cat /etc/hosts | mailx -s "TEST" myemail@mydomain.com

Now you will be able to execute a script or run a command and send the output to an email address.

Conclusion

It is very easy to run a command and send the output to an email. Understanding how the pipe operator works is integral. For further reading see the links below.

Exit mobile version