views:

67

answers:

4

I have a program (grabface) that takes a picture of the face of a person using a webcam, and I also have a shell script wrapper that works like this:

On the command line the user gives the script the name of a program to run and its command line arguments. The script then executes the given command and checks the exit code. If there was an error the program grabface is run to capture the surprised face of the user.

This all works quite well. But the problem is that the wrapper script must always be used. Is there some way to automatically run this script whenever a command is entered in the shell? Or is there some other way to automatically run a given program after any program is run?

Preferably the solution should work in bash, but any other shell is also OK. I realize this could be accomplished by simply making some adjustments in the source code of the shell, but that's kind of a last measure.

Something that is probably even trickier would be to extend this to work with programs launched outside of the shell as well (e.g. from a desktop environment) but this may be too difficult.

Edit: Awsome! Since bash was so easy, what about other shells?

+3  A: 

In Bash, you can use the trap command with an argument of ERR to execute a specified command whenever an executed command returns non-zero.

$ trap "echo 'there was an error'" ERR
$ touch ./can_touch
$ touch ./asfdsafds/fdsafsdaf/fdsafdsa/fdsafdasfdsa/fdsa
touch: cannot touch `./asfdsafds/fdsafsdaf/fdsafdsa/fdsafdasfdsa/fdsa': No such file or directory
there was an error

trap affects the whole session, so you'll need to make sure that trap is called at the beginning of the session by putting it in .bashrc or .profile.

Mark Rushakoff
+1  A: 

In the .profile of the user add:

trap grabface ERR
Aaron Digulla
+1  A: 

Other special trap signals that Bash understands are: DEBUG, RETURN and EXIT as well as all the system signals (which can be listed using trap -l).

The Korn shell has a similar facility, while the Z shell has a more extensive trap capability.

By the way, in some cases for the command line, it can be useful in Bash to set the PROMPT_COMMAND variable to a script or command that will be run each time the prompt is issued.

Dennis Williamson
A: 

Just subtitute your command where I have the false.
false || echo "It failed"

If you want to do the oposite, like when it succeeds, just put your command instead of true:
true && echo "It succeeded"

Arkaitz Jimenez
Sure, but this doesn't really answer the question. As I already said, I have a wrapper script that basically does that. What I wanted to know was how I could get the script to run without having to type anything extra in the shell (like the '|| echo "It failed"' in your example)
pafcu