Take the 2-minute tour ×

I hope the title of this question isn't too confusing.

What I want to do is send myself an e-mail when a specified command has finished running in the shell. For this purpose, I wrote a simple script that takes an argument and sends me an e-mail with the argument as the messages text. The idea is to be able to execute a command that I know will take a long time in the following manner:

./commandThatTakesALongTime; ./emailingScript <some argument>

The obvious answer here is to just write the name of the command again, and pass it in as a string but often I'll have commands with lots of arguments, and so I'd prefer it to automatically grab what was executed.

I've tried using various combinations of !!:p, but that doesn't appear to be working. Any tips?

ETA: I'm looking for something that I can pass as which will basically just print "./commandThatTakesALongTime"--does such a thing exist? The reason I'm doing it this way is because I need my environment to be preserved as it is after the command is executed.

share|improve this question

1 Answer 1

Write a script like this:


if "$@" ; then
    echo "$@" | mail -s 'command complete' some@email.address
    echo "Command failed!"

Save this as exec_and_mail and make it executable.

You run it as exec_and_mail some_command -with arguments --passed --to it.

share|improve this answer
Question, which should've been stated in the original problem definition--will this preserve my environment? Some of the programs that I have that are longer-running are changing environment variables and those need to be preserved. Thanks. –  smintitule May 19 at 19:16
You cannot pass environment variables from a child process to the parent. The child inherits the parent environment and can modify it, but it's not going to affect the parent environment in any way. There are workaround to this and they amount to passing a script to the parent which sets the environment variables. –  Sigi May 19 at 19:17
In other words: nothing that a command does to its environment will affect the environment of the process (or shell) that executed the command. So your environment will not be modified. –  Sigi May 19 at 19:20
Which I think brings me back to where I started--sequentially executing two commands and just breaking them up with the semicolon. The issue is just what do I send to my script as an argument? –  smintitule May 19 at 19:21
There's no way for a script to get information from the rest of the command line. That's why this script takes the command line as an argument, and it executes the command for you. It will inherit your environment variables. –  Barmar May 19 at 19:34

Your Answer


