Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 420
pafcu Avatar asked Sep 02 '25 05:09

pafcu


1 Answers

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.

like image 133
Mark Rushakoff Avatar answered Sep 04 '25 20:09

Mark Rushakoff