Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run command in the background and notify me via email when done

Tags:

linux

bash

shell

I have the following command which will take ages to run (couple of hours). I would like to make it a background process and for it to send me an email when its done.

For the cherry on the top, any errors it encountered should write to a text file when an error has occurred?

find . -type f -name "*.rm" -exec ./rm2mp3.sh \{} \; -exec rm \{} \;

How can I do this with my above command?

like image 719
Abs Avatar asked Jun 02 '10 23:06

Abs


People also ask

How do I run a command in the background?

If you want to run additional commands while a previous command runs, you can run a command in the background. If you know you want to run a command in the background, type an ampersand (&) after the command as shown in the following example. The number that follows is the process id.

What way can you execute command in background if you logout?

Option 2: bg + disown. If you want to "background" already running tasks, then Ctrl + Z then run bg to put your most recent suspended task to background, allowing it to continue running. disown will keep the process running after you log out. The -h flag prevents hangup.

When you run a command what happens in the background?

When you run a command in the background, you do not have to wait for the command to finish before running another command. A job is another name for a process running a pipeline (which can be a simple command). You can have only one foreground job on a screen, but you can have many background jobs.

How do I email a shell script output?

Run `mail' command by '-s' option with email subject and the recipient email address like the following command. It will ask for Cc: address. If you don't want to use Cc: field then keep it blank and press enter. Type the message body and press Ctrl+D to send the email.


1 Answers

yourcommand 2>&1 | mail -s "yourcommand is done" [email protected]

The 2>&1 bit says "make my errors like the regular output", and the rest says "take the regular output and mail it to me with a nice subject line"

Note that it doesn't work in csh family of shells, only Bourne (sh, bash, ksh...), AFAIK. Thus, run under #!/bin/sh or #!/bin/bash. (N.B. You can pipe both descriptors in csh using yourcommand |& mail ..., but only a madman writes scripts using csh.)

UPDATE:

How would I write the errors to a log file and then just email my self on completion?

if you mean just email the fact that it is done,

yourcommand 1>/dev/null 2>mylogfile ; (echo "done!" | mail -s "yourcommand is done")

if you mean just email the errors (in which case you don't need the log file) (fixed as @Trey said),

yourcommand 2&>1 1>/dev/null | mail -s "yourcommand is done" [email protected]
like image 185
Amadan Avatar answered Oct 07 '22 16:10

Amadan