1

I have a bash script that runs a bunch of various commands. It takes a while to run and I would like an audible cue if any of the commands fail, so I can be doing something else but still know as soon as a failure has occurred. Is there a way to play a sound the first time a command fails?

Two related Stack Overflow questions:

  1. By using set -e, it's possible to make a bash script exit on the first error. This is what I'm currently using as it's a very clean mechanism - no need to check error codes on each command. If there's a way to use this with the equivalent of a "finally" block where I can specify what should happen before exit, that would work.
  2. A beep noise apparently can be played by echoing an ASCII code, so even if I'm just able to make one of these simple calls on first error.

Side note: I really am after a simple sound - no need to SMS/tweet/post to Instagram.

Community
  • 1
  • 1
Bryce Thomas
  • 10,479
  • 26
  • 77
  • 126

1 Answers1

4

help trap tells us that "A SIGNAL_SPEC of ERR means to execute ARG each time a command's failure would cause the shell to exit when the -e option is enabled.":

#!/bin/bash

exit_with_bells() {
    printf '\a'           # Ring terminal bell
    mplayer ~/"some.mp3"  # Play an audio file
    exit 1                # Exit with error
}

trap 'exit_with_bells' ERR

set -e
your commands here
that other guy
  • 116,971
  • 11
  • 170
  • 194