pafcu
pafcu

Reputation: 8128

Automatically run a program if another program returns an error

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?

Upvotes: 4

Views: 1335

Answers (4)

Arkaitz Jimenez
Arkaitz Jimenez

Reputation: 23168

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"

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 359965

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.

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328556

In the .profile of the user add:

trap grabface ERR

Upvotes: 1

Mark Rushakoff
Mark Rushakoff

Reputation: 258148

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.

Upvotes: 6

Related Questions