smintitule
smintitule

Reputation: 43

How do I capture the current command and send it into a script as an argument?

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.

Upvotes: 1

Views: 85

Answers (1)

Sigi
Sigi

Reputation: 1864

Write a script like this:

#!/bin/bash

if "$@" ; then
    echo "$@" | mail -s 'command complete' [email protected]
else
    echo "Command failed!"
fi

Save this as exec_and_mail and make it executable.

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

Upvotes: 3

Related Questions