Bash – Run a Command and Email the Output

bashshell-scriptssh

I'm new to bash scripting. I have a CentOS server. I'd like to run a command, something very simple like :

service lfd status

and then email that output to my email. Can someone help me with this, please?
ultimately this is what i wanted to do : create a bash script like lfd.sh, run that bash script every 1 hour. So when i run that bash script, it will run this command "service lfd status" and send me the output via email..

Best Answer

Based on the other answers and OP's comments to the other answers, I think I can suggest an answer.

1.You want to run a command an email the output of it to some email. You have several options for sending mail on Linux. You'll need to make sure you can actually send email before your command can do it. Use a program like mail or mailx.

sudo yum install mailx

For more instructions configuring the mailx program, follow the directions here - https://www.digitalocean.com/community/tutorials/how-to-send-e-mail-alerts-on-a-centos-vps-for-system-monitoring

You could also use python or any programming language, but I'll forego that for now for simplicity.

2.Once mailx is setup based on the instructions in digitalocean, you should now be able to send emails like this:

echo "Your message" | mail -s "Message Subject" email@address

If you get that email, perfect! We're ready for the next part. Create your file lfd.sh

#!/bin/bash

service lfd status | mail -s "LFD Status" youremail@address.com

That should be all it takes to get the output of service lfd status emailed to you. If you want to run that, make sure you make it executable by running

chmod +x ./lfd.sh

So that should send you an email, but we're not done yet. You also mentioned you wanted it to automatically send you an email every hour. This can be done with crontab.

Crontab/Cron is a very useful automatic task scheduler on Linux. You'll need to create a Cron job with your lfd.sh

Websites like this help me remember the syntax for a Cron job.

crontab -e
0 * * * * /home/username/lfd.sh

That should run the job once every hour, at the top of the hour, every day of the week, if every month. For more info on that, view the Cron link or Google Cron examples.

Related Question